如何计算字节数组的crc?

时间:2017-07-19 13:03:36

标签: c embedded crc

我理解一个字节的CRC如何通过模2除法用多项式计算,但我不明白你如何计算由字节数组组成的数据的CRC。单个字节的CRC可以通过以下代码计算

#define WIDTH  8
#define TOPBIT 1 << 7
#define POLYNOMIAL 0xD8

uint8_t(uint8_t const message)
{
    uint8_t remainder = 0;  
    remainder ^= message;
    for (uint8_t bit = 8; bit > 0; --bit)
    {
        if (remainder & TOPBIT)
        {
            remainder = (remainder << 1) ^ POLYNOMIAL;
        }
        else
        {
            remainder = (remainder << 1);
        }
    }
    return (remainder);

}

但字节数组怎么样?我在this site上找到了上面的代码,作者还给出了字节数组的代码,他只是将当前余数与下一个字节进行异或

remainder ^= (message[byte] << (WIDTH - 8));

我不明白为什么?他为什么要把下一个字节输入到余数中?

2 个答案:

答案 0 :(得分:1)

A painless guide to CRC error detection algorithms。它包含了CRC上的所有内容,包括您的问题。数组被视为单个大量数字,因此余数被转移到下一个字节。 CRC是最后留下的剩余部分。

答案 1 :(得分:0)

查看维基百科上的页面Mathematics of cyclic redundancy checks事实证明,CRC是一个线性运算,意味着crc(x ^ y ^ z)= crc(x)crc(y)crc(x)因此作者XOR用前一个字节的剩余部分和下一个字节