注:这里的生成多项式是发送端和接收端一起约定的。(可人为取值,也可取一般的常用值) CRC校验只是知道接收端接收到的数据正确与否,如果发现错了那就丢弃,并不能检查出到底是哪一位发送的数据出现了错误。
//CRC4 #include <stdint.h> #include <stdio.h> #define POLYNOMIAL 0xC8 /* 11011后面补0凑8位数:11011000*/ uint8_t CheckCrc4(uint8_t const message) { uint8_t remainder; //余数 uint8_t i = 0; //循环变量 remainder = message; /* 初始化,余数=原始数据 */ for (i = 0; i < 8; i++) /* 从最高位开始依次计算 */ { if (remainder & 0x80) { remainder ^= POLYNOMIAL; } remainder = (remainder << 1); } return (remainder >> 4);/* 返回计算的CRC码 */ } int main(void) { uint8_t dat = 0xB3; uint8_t crc = CheckCrc4(dat); printf("crc = %#x\n", crc); if(crc == 0x4) { printf("ok.\n"); } else { printf("fail.\n"); } return 0; } //CRC8 uint8_t CheckCrc8(uint8_t* const message, uint8_t initial_value) { uint8_t remainder; //余数 uint8_t i = 0, j = 0; //循环变量 /* 初始化 */ remainder = initial_value; for(j = 0; j < 2;j++) { remainder ^= message[j]; /* 从最高位开始依次计算 */ for (i = 0; i < 8; i++) { if (remainder & 0x80) { remainder = (remainder << 1)^CRC8_POLYNOMIAL; } else { remainder = (remainder << 1); } } } return remainder;/* 返回计算的CRC码 */ } int main(void) { char dat[2] = { 0xBE,0xEF }; uint8_t crc = CheckCrc8(dat, 0xFF); printf("crc = %#x\n", crc); if (crc == 0x92) { printf("ok.\n"); } else { printf("fail.\n"); } return 0; }