C语言 CRC代码和实现兼容性



CRC校验和的机制或步骤很简单,但是软件在某种程度上要复杂得多,并且软件中的一些步骤与CRC的步骤不兼容下图是获取CRC校验和的步骤(它只是一个模2除法):

校验和为余数 = 001
用于计算CRC校验和的软件是一串位是:

/*
 * The width of the CRC calculation and result.
 * Modify the typedef for a 16 or 32-bit CRC standard.
 */
typedef uint8_t crc;
#define WIDTH  (8 * sizeof(crc))
#define TOPBIT (1 << (WIDTH - 1))
crc
crcSlow(uint8_t const message[], int nBytes)
{
    crc  remainder = 0; 

    /*
     * Perform modulo-2 division, a byte at a time.
     */
    for (int byte = 0; byte < nBytes; ++byte)
    {
        /*
         * Bring the next byte into the remainder.
         */
        remainder ^= (message[byte] << (WIDTH - 8));
        /*
         * Perform modulo-2 division, a bit at a time.
         */
        for (uint8_t bit = 8; bit > 0; --bit)
        {
            /*
             * Try to divide the current data bit.
             */
            if (remainder & TOPBIT)
            {
                remainder = (remainder << 1) ^ POLYNOMIAL;
            }
            else
            {
                remainder = (remainder << 1);
            }
        }
    }
    /*
     * The final remainder is the CRC result.
     */
    return (remainder);
}

我看到part( remainder<<1 )中的软件不兼容,因为即使以下位不是 0,移位也会始终在右侧加 0。

以及部分: remainder ^= (message[byte] << (WIDTH - 8));

放置第一个字节时,我没有看到问题,因为初始值是因为初始值为 0,但是在插入下一个字节时,为什么我们将它们的每个字节与前一个余数

代码示例似乎使用可变大小的CRC,其中CRC的大小为WIDTH。多项式是 WIDTH+1 位多项式的底部宽度位,其最低有效位设置为 1。由于操作是 XOR,因此数据位与余数的 XOR 顺序无关紧要,因此 8 个数据位可以同时异或到余数的上位。然后,一次反馈周期的位发生8位。由于多项式的底部位是 1,只要数据中有任何 1 位,就会保持循环。

最新更新