【问题标题】:crc-16 IBM, 0x00 not taken in considerationcrc-16 IBM, 0x00 未考虑
【发布时间】: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 传递为 ab

标签: arrays c crc16


【解决方案1】:

您的 CRC 例程给出了正确的结果。是你的测试错了。 strlen(p) 返回p 的第一个零字节之前的字节数。对于buf2,这是四个,而不是您想要的五个。对于buf1,它甚至没有被定义,因为在那个数组之后内存中可能有任何东西。如果编译器碰巧在数组后面放了零,你可能会得到四个。

对于测试,您只需手动提供len(buf1, 4), (buf2, 5).

顺便说一句,该代码可能更有效。它不必每次都用b 进行测试。只需与b 进行异或运算即可获得相同的效果:

    crc ^= buf[j];
    for (unsigned char i = 0; i < 8; i++)
        crc = crc & 1 ? (crc >> 1) ^ 0xa001 : crc >> 1;

【讨论】:

  • 感谢您的澄清。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 1970-01-01
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多