c - CRC 算法实现



我正在用C实现CRC16算法,它是:

init = 0x0000 as long as the data stream goes on if the first bit of data is not equal to the first bit of initial value init = leftshift init once and xor it with the polynomial otherwise leftshift init go to the next data bit init = CRC Checksum

现在的问题是...如果我在第一次比较后更改 init 值,它将始终等于数据流。

例如:如果我得到的初始值为

1011 0000 1011 0101

和数据流

0011 0110 1000 0101

第一次迭代后。

它们将永远相等,因为开始时的0's无关紧要,可以忽略不计。

在下一次迭代之后,它们将是:

011 0000 1011 0101

和数据流

011 0110 1000 0101

但同样,0's可以被忽略,我们得到了平等。

我真的很困惑。

这是我的 C 代码:

#define POLY 0x8005
int crc = 0x0000;   // Initial value
char data[1024];
int *dp = data;
int fd, nread;
fd = open(argv[1], O_RDWR);
nread = read(fd, data, sizeof(data));
int *end = dp + nread;

while(data < end)
{
    crc = crc & 1 && data & 1 ? crc << 1 : (crc << 1) ^ POLY;
    data++;
}

几个问题:

  1. 您正在操作最低有效位,但应该在最高有效位上工作。这可能是导致您对位保持不变感到困惑的原因,因为您正在查看值的错误一端。

  2. crc & 1 && data & 1检查位是否等于 1,而不是检查它们是否彼此相等。

  3. 您似乎对data是数组(如声明)、整数(如data & 1中使用)还是指针(如data++中使用)感到困惑。

  4. 如果将指针data更改为指针,并在每一步将其递增 1,则意味着仅处理每个输入字节中的一个位。您需要一个内部循环来处理所有 8 位。