CRC16的C语言算法:
#define PRESET_VALUE 0xFFFF
#define POLYNOMIAL 0x8408
unsigned int uiCrc16Cal(unsigned char const * pucY, unsigned char ucX)
{
unsigned char ucI,ucJ;
unsigned short int uiCrcValue = PRESET_VALUE;
for(ucI = 0; ucI < ucX; ucI++)
{
uiCrcValue = uiCrcValue ^ *(pucY + ucI);
for(ucJ = 0; ucJ < 8; ucJ++)
{
if(uiCrcValue & 0x0001)
{
uiCrcValue = (uiCrcValue >> 1) ^ POLYNOMIAL;
}
else
{
uiCrcValue = (uiCrcValue >> 1);
}
}
}
return uiCrcValue;
}
pucY是要计算CRC16的字符数组的入口,ucX是字符数组中字符个数。
上位机收到数据的时候,只要把收到的数据按以上算法进行计算CRC16,结果为0x0000表明数据正确。