【发布时间】:2022-01-17 02:14:13
【问题描述】:
我确实测试了我在网上找到的 crc-16/ibm 实现。当我用十六进制字节数组测试它时,它工作正常,但如果我包含一些 0x00 值,那么它不会给出正确的结果。 这是它的代码
unsigned short ComputeCRC16(const unsigned char* buf, unsigned int len) {
unsigned short crc = 0;
for (unsigned int j = 0; j < len; j++)
{
unsigned char b = buf[j];
for (unsigned char i = 0; i < 8; i++)
{
crc = ((b ^ (unsigned char)crc) & 1) ? ((crc >> 1) ^ 0xA001) : (crc >> 1);
b >>= 1;
}
}
return crc;
}
我用这段代码测试了它:
int main() {
//fe b5 5f f7
unsigned char buf1[4096] = { 0xfe, 0xb5, 0x5f, 0xf7 };
//fe b5 00 5f f7 00
unsigned char buf2[4096] = { 0xfe, 0xb5, 0x00, 0x5f, 0xf7, 0x00 };
int a = strlen(buf1);
unsigned short res = ComputeCRC16(buf1, a);
printf("res = %04x\n", res); //res : 7858, the result is correct
int b = strlen(buf2);
unsigned short res = ComputeCRC16(buf2, b);
printf("res = %04x\n", res); //res : d781, the result is not correct
return 0; //the correct result : 26EE
}
为了验证我使用这个网站的结果: https://www.lammertbies.nl/comm/info/crc-calculation
【问题讨论】:
-
不要使用
strlen,它最多计数到第一个0字节,通常用于字符串,而不是任意二进制数据。.. -
如何计算输入数组的大小?
-
在您的情况下,您可以使用
sizeof,因为数组是静态的(根据编译器的已知大小,而不是存储类)。如果不是,您将不得不通过其他方式跟踪大小。 -
即使使用 sizeof() 也不起作用。
-
对.. 因为你的数组的大小是固定的
4096,没有注意到它。更改为unsigned char buf1[] = { 0xfe, 0xb5, 0x5f, 0xf7 };和unsigned char buf2[] = { 0xfe, 0xb5, 0x00, 0x5f, 0xf7, 0x00 };或者分别将 4 和 5 传递为a和b