引言
CRC原理
https://blog.csdn.net/qq_29506411/article/details/110477039#CRC-8%20%E6%A0%A1%E9%AA%8C
函数实现
数据反序函数
// 字节数据反序
unsigned char reversal_data(unsigned char dat){
unsigned char temp = 0;
for(unsigned char i=0;i<8;i++){
if(dat&0x80){
temp |= 0X01<<i;
}
dat =dat<<1;
}
return temp;
}
CRC8校验函数
// poly;多项式 init:初始值
//ref_in 当 ref_in = 1时输入反序 否则不反序
//ref_out 当 ref_out = 1时输出反序 否则不反序
//di 待校验CRC数组 len 校验数据长度
unsigned char SY_CRC_8(unsigned char poly,unsigned char init,unsigned char ref_in,unsigned char ref_out, unsigned char *di,unsigned char len)
{
unsigned char crc_poly ;
unsigned char data_t;
unsigned char temp = 0;
crc_poly = poly;//0X13 ---》 X^8+X^4+X^1+1 total 8 effective bits without X^8.
data_t = init; //初始值
while(len--)
{
if(ref_in){
data_t ^=reversal_data(*di++);
}else {
data_t ^= *di++;
}
for (unsigned char i=8; i>0; --i)
{
if (data_t & 0x80)
data_t = (data_t<<1) ^ crc_poly;
else
data_t = (data_t<<1);
}
}
if(ref_out){
temp = data_t;
data_t = reversal_data(temp);
}
return (data_t);
}
测试demo
int main()
{
/* Write C code in this online editor and run it. */
unsigned char CRC = 0;
unsigned char buff[]={0x011,0x22};
CRC = SY_CRC_8(0x13,0xcb,1,1,buff,2); // 多项式0X13 初始值0XCB ,输入反序
printf("CRC8 = 0x%02X \n",CRC);
return 0;
}