网络上CRC讲解很多优秀帖子:1的参考文献很厉害,且带有源码
1、一文详解循环冗余校验校验算法(CRC校验)及C语言代码的实现 ---- 以CRC-16/MODBUS为例讲解
如下是c语言代码,支持crc32、crc16查表法计算代码,支持配置初始化值与多项式算法
void crc_init_crc32_table(unsigned int crc_poly, unsigned int *crc_table)
{
unsigned int i;
unsigned int j;
for (i = 0; i < 256; i++) {
unsigned int temp = i << 24;
for (j = 0; j < 8; j++) {
temp = (temp << 1) ^ (crc_poly * ((temp >> 31) & 0x1));
}
crc_table[i] = temp;
}
}
void crc_init_crc16_table(short int crc_poly, short int *crc_table)
{
unsigned int i;
unsigned int j;
for (i = 0; i < 256; i++) {
short int temp = i << 8;
for (j = 0; j < 8; j++) {
temp = (temp << 1) ^ (crc_poly * ((temp >> 15) & 0x1));
}
crc_table[i] = temp;
}
}
unsigned int crc_hash_calc_crc32(unsigned int init, unsigned int poly, uint8 *byte_input, unsigned int len)
{
unsigned int loop = len;
unsigned int crc_table[256] = { 0 };
crc_init_crc32_table(poly, crc_table);
unsigned int i;
unsigned int temp;
unsigned int crc_val = init;
unsigned int old_crc;
unsigned int input;
for (i = 0; i < loop; i++) {
input = byte_input[i];
crc_val = crc_val ^ (input << 24);
temp = crc_val >> 24;
old_crc = crc_table[temp];
crc_val = (crc_val << 8) ^ old_crc;
}
return crc_val;
}
unsigned int crc_hash_calc_crc16(unsigned int init, unsigned int poly, uint8 *byte_input, unsigned int len)
{
unsigned int loop = len;
short int crc_table[256] = { 0 };
crc_init_crc16_table(poly, crc_table);
short int i;
short int temp;
short int crc_val = init;
short int old_crc;
short int input;
for (i = 0; i < loop; i++) {
input = byte_input[i];
crc_val = crc_val ^ (input << 8);
temp = crc_val >> 8;
old_crc = crc_table[temp];
crc_val = (crc_val << 8) ^ old_crc;
}
return crc_val;
}