以下给出两种在C语言中计算CRC-16校验码的函数及其使用方法,其中第一种参考了如下博客中的通用代码,进行修改后得到专门计算CRC-16的校验码,已实践,均正确可用~
https://blog.csdn.net/ydyuse/article/details/105395368
第一种: 使用方法:前三个参数固定,第四个是存储要校验数据的数组,第五个是利用数组中前8个数据来进行CRC校验。该函数返回值即为它的CRC-16校验码。
crc_val = cal_CRC16(0xffff,0x8005,0,buff, 8);
/**CRC校验码计算函数**/
uint16_t cal_CRC16(uint16_t wCRCin,uint16_t wCPoly,uint16_t wResultXOR,uint8_t *puchMsg, uint8_t usDataLen)
{
uint8_t wChar = 0;
while (usDataLen--)
{
wChar = *(puchMsg++);
//输入值反转
uint8_t temp_char = wChar;
wChar=0;
for(int i=0;i
if (wCRCin & 0x8000)
wCRCin = (wCRCin
uint16_t crc = 0xFFFF;
for (int pos = 0; pos
if ((crc & 0x0001) != 0) // If the LSB is set
{
crc >>= 1; // Shift right and XOR 0xA001
crc ^= 0xA001;
}
else // Else LSB is not set
{
crc >>= 1; // Just shift right
}
}
}
crc = ((crc & 0x00ff) 8);
//DBG_printf("%s crc = 0x%04x\n", __func__, crc);
return crc;
}
|