首页 > 解决方案 > 如果最高有效字节的最高有效位为 1,则样本为负

问题描述

嗨,我正在做一个关于音频处理的项目

代码工作正常,但我不明白这三行

如果有人知道这些代码行的内容

// Otherwise, if the most-significant bit of most-significant byte is 1, then
// sample is negative, so we need to set the upper bytes to all 1s.
else if (sampleBytes[bytesPerSample-1] & 0x80)
{
    for (size_t b = bytesPerSample; b < sizeof(sample); b++)
    {
        sampleBytes[b] = 0xFF;
    }
}

标签: c++audiowav

解决方案


该行将带有放置在“sampleBytes”中的“bytesPerSample”字节的数字扩展到与“sample”变量一样多的字节,如果它是负数,则用一个完成。

在大多数系统中,负数以二进制形式表示为两个补码形式(https://en.wikipedia.org/wiki/Two%27s_complement)。也就是说,-x = NOT(x) + 1。

For example:
11111111 = 1
11111110 = 2
11111101 = 3
11111100 = 4
...

因此,如果数字为负数,则必须使用要扩展的数字来完成,以保持该值。

第一行断言数字是否为负,第二行通过额外的字节进行迭代,最后将这些字节放入十六进制。


推荐阅读