概念
CRC校验算法,说白了,就是把需要校验的数据与多项式进行循环异或(XOR), 进行XOR的方式与实际中数据传输时,是高位先传、还是低位先传有关。对于数据
高位先传的方式,XOR从数据的高位开始,我们就叫它顺序异或吧;对于数据低位先传的方式,XOR从数据的低位开始,我们就叫它反序异或吧。两种不同的异或方式, 即使
对应相同的多项式,计算出来的结果也是不一样的。
实例解析
两种不同类型的写法:
#include <stdio.h>
typedef unsigned char uint8_t;
uint8_t gencrc(uint8_t *data, size_t len)
{
uint8_t crc = 0xff;
size_t i, j;
for (i = 0; i < len; i++) {
crc ^= data[i];
for (j = 0; j < 8; j++) {
if ((crc & 0x80) != 0)
crc = (uint8_t)((crc << 1) ^ 0x31);
else
crc <<= 1;
}
}
return crc;
}
/*
crc8 poly = 0x107 (x8+x2+x1+1)
*/
uint8_t crc8(uint8_t *data, int size)
{
uint8_t crc = 0x00;
uint8_t poly = 0x07;
int bit;
while (size--)
{
crc ^= *data++;
for (bit = 0; bit < 8; bit++)
{
if (crc & 0x80)
{
crc = (crc << 1) ^ poly;
}
else
{
crc <<= 1;
}
}
}
return crc;
}
int main()
{
uint8_t data[8] = {0xBE,0xEF,0,0,0,0,0,0};
uint8_t datab[8] = {0xBE,0xEF,2,0,0,0,0,0};
uint8_t crc,crcb;
crc = gencrc(data, 8);
crcb = gencrc(datab, 8);
printf("first crc:
");
printf("crc:0x%1x crcb:0x%x
", crc,crcb);
crc = crc8(data, 8);
crcb = crc8(datab, 8);
printf("second crc:
");
printf("crc:0x%1x crcb:0x%x
", crc,crcb);
crc = gencrc(data+2, 1); /* returns 0xac */
printf("%1x
", crc);
return 0;
}
参数不同结果:
first crc:
crc:0xc7 crcb:0x69
second crc:
crc:0x83 crcb:0xd1
ac