【发布时间】:2018-11-20 13:58:55
【问题描述】:
Need fastest way to convert 2's complement to decimal in C 有人问过类似的问题,但我无法用它来获得答案,所以发布这个...
我有来自音频传感器的 32 位数据,格式如下:- 数据格式是 I2S,24 位,2 的补码,MSB 优先。数据精度为18位;未使用的位为零。
无需任何音频输入,我就能从传感器读取以下数据:-
- 0xFA578000
- 0xFA8AC000
- 0xFA85C000
- 0xFA828000
- 0xFA800000
- 0xFA7E4000
- 0xFA7D0000
- 0xFA7BC000
等等……
我需要使用这些数据样本来计算它们的 RMS 值,然后进一步使用这个 RMS 值来计算分贝 (20 * log(rms))。
这是我的 cmets 代码:-
//I have 32-bits, with data in the most-significant 24 bits.
inputVal &= 0xFFFFFF00; //Mask the least significant 8 bits.
inputVal = inputVal >> 8; //Data is shifted to least 24 bits. 24th bit is the sign bit.
inputVal &= 0x00FFFFC0; //Mask the least 6 bits, since data precision is 18 bits.
//So, I have got 24-bit data with masked 6 lsb bits. 24th bit is sign bit.
//Converting from 2's complement.
const int negative = (inputVal & (1 << 23)) != 0;
int nativeInt;
if (negative)
nativeInt = inputVal | ~((1 << 24) - 1);
else
nativeInt = inputVal;
return (nativeInt * nativeInt); //Returning the squared value to calculate RMS
在此之后,我取 平方和的平均值并计算其根以获得 RMS 值。
我的问题是,
- 我是否正确地进行了数据位操作?
- 是否需要将数据样本从 2 的补码转换为整数来计算它们的 RMS 值?
****************************************************第2部分*********************************************** ******
继续@Johnny Johansson 的回答:-
看起来您的所有样本值都接近 -6800,所以我认为这是您需要考虑的偏移量。
为了标准化样本集,我计算了样本集的平均值,并从样本集中的每个值中减去它。
然后,我从样本集中找到了最大值和最小值,并计算了峰峰值。
// I have the sample set, get the mean
float meanval = 0;
for (int i=0; i <actualNumberOfSamples ; i++)
{
meanval += samples[i];
}
meanval /= actualNumberOfSamples;
printf("Average is: %f\n", meanval);
// subtract it from all samples to get a 'normalized' output
for (int i = 0; i < actualNumberOfSamples; i++)
{
samples[i] -= meanval;
}
// find the 'peak to peak' max
float minsample = 100000;
float maxsample = -100000;
float peakToPeakMax = 0.0;
for (int i = 0; i < actualNumberOfSamples; i++)
{
minsample = fmin(minsample, samples[i]);
maxsample = fmax(maxsample, samples[i]);
}
peakToPeakMax = (maxsample - minsample);
printf("The peak-to-peak maximum value is: %f\n", peakToPeakMax);
(这不包括 RMS 部分,它是在您拥有正确的有符号整数值之后出现的)
现在,我通过将峰峰值除以 2 的平方根来计算 rms 值。 然后,20 * log10(rms) 给了我相应的分贝值。
rmsValue = peak2peakValue / sqrt2;
DB_Val = 20 * log10(rmsValue);
- 上面的代码是否处理了您提到的“偏移量”?
- 我还没有找到一个测试计划来验证计算的分贝,但我是否正确地用数学计算了分贝值?
【问题讨论】:
-
第一行
inputVal &= 0xFFFFFF00中的掩码是多余的,因为无论如何您都要将这些位移出 -
关于第 2 部分:偏移部分看起来不错,但除此之外我不确定发生了什么。我看不到任何 RMS 计算的迹象,使用峰值对我来说看起来很奇怪。 (虽然我实际上并不知道如何从这种数据中计算 dB)。也许最好问一个关于将你拥有的数据转换为 dB 值的新问题......
-
非常感谢!我将提出一个关于将值转换为 dB 的新问题。你的建议很有帮助。再次感谢:-)
标签: c bit-manipulation twos-complement