如何用C语言写巴特沃斯高通滤波器,要求输入输出均为长整型
时间: 2024-03-17 19:41:04 浏览: 100
巴特沃斯滤波的C语言实现
3星 · 编辑精心推荐
巴特沃斯高通滤波器是一种数字滤波器,用于滤除低频信号并保留高频信号。下面是一个用C语言实现巴特沃斯高通滤波器的示例代码,输入输出均为长整型:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define M_PI 3.14159265358979323846
long b[3]; // 分子系数
long a[3]; // 分母系数
long x[3]; // 输入信号
long y[3]; // 输出信号
void butterworth_highpass_filter(long fc, int fs, double Q)
{
double w0 = 2 * M_PI * fc / fs;
double alpha = sin(w0) / (2 * Q);
double cosw0 = cos(w0);
double alpha2 = alpha * alpha;
b[0] = (long)((1 - cosw0) / 2 * pow(2, 30));
b[1] = (long)((1 - cosw0) * pow(2, 30));
b[2] = (long)((1 - cosw0) / 2 * pow(2, 30));
a[0] = pow(2, 30) + (long)(alpha * pow(2, 30));
a[1] = (long)(-2 * cosw0 * pow(2, 30));
a[2] = pow(2, 30) - (long)(alpha * pow(2, 30));
double gain = 1 / (double)a[0];
b[0] = (long)(b[0] * gain);
b[1] = (long)(b[1] * gain);
b[2] = (long)(b[2] * gain);
a[1] = (long)(-a[1]);
a[2] = (long)(-a[2]);
x[0] = x[1] = x[2] = 0;
y[0] = y[1] = y[2] = 0;
}
long butterworth_highpass_filter_apply(long input)
{
x[2] = x[1];
x[1] = x[0];
x[0] = input;
y[2] = y[1];
y[1] = y[0];
y[0] = (long)((b[0] * x[0] + b[1] * x[1] + b[2] * x[2] - a[1] * y[1] - a[2] * y[2]) / (double)a[0]);
return y[0];
}
int main()
{
long fc = 1000; // 截止频率为1kHz
int fs = 8000; // 采样率为8kHz
double Q = 0.707; // 质因数Q为0.707
butterworth_highpass_filter(fc, fs, Q);
// 生成测试信号,1s的8000Hz正弦波
int num_samples = 8000;
long test_signal[num_samples];
for (int i = 0; i < num_samples; i++) {
test_signal[i] = (long)(sin(2 * M_PI * i * 1000 / fs) * pow(2, 30));
}
// 对测试信号进行滤波
long filtered_signal[num_samples];
for (int i = 0; i < num_samples; i++) {
filtered_signal[i] = butterworth_highpass_filter_apply(test_signal[i]);
}
// 将结果输出到文件
FILE *fp = fopen("filtered_signal.txt", "w");
if (fp == NULL) {
printf("Failed to open file\n");
return 1;
}
for (int i = 0; i < num_samples; i++) {
fprintf(fp, "%ld\n", filtered_signal[i]);
}
fclose(fp);
return 0;
}
```
在这个示例中,我们首先定义了一个 `butterworth_highpass_filter` 函数,用于计算巴特沃斯高通滤波器的分子和分母系数。然后,我们定义了一个 `butterworth_highpass_filter_apply` 函数,用于对输入信号进行滤波。在 `main` 函数中,我们首先生成了一个1秒钟的正弦波作为测试信号,然后对其进行滤波,并将结果输出到文件中。
需要注意的是,在这个示例中,我们将输入信号和输出信号都乘以了 $2^{30}$,以避免在计算过程中出现浮点运算误差。在使用时,需要根据具体的需求进行修改。
阅读全文