由于网上的CRC16标准算法很多,在实现CRC16算法时网上都是不同的算法有不同的函数,我觉得这样很不方便,所以自己实现了一个通用的CRC16算法:
/*************************************************
Function: calculate_crc16
Description: 通用的16位CRC校验算法
Input: wCRCin:CRC16算法的初始值
wCPoly:特征多项式
wResultXOR:结果异或值
input_invert:输入值是否反转
ouput_invert:输出值是否反转
puchMsg:开始校验的数据的起始地址
usDataLen:校验的数据长度
Output: 无输出
Return: 16位CRC校验结果
Others: example:CRC-16/CCITT由本函数实现则填充参数如下:
calculate_crc(0,0x1021,0,true,true,puchMsg,usDataLen)
*************************************************/
quint16 calculate_crc16(quint16 wCRCin,quint16 wCPoly,quint16 wResultXOR,bool input_invert,bool ouput_invert,const char *puchMsg, int usDataLen)
{
quint8 wChar = 0;
while (usDataLen--)
{
wChar = *(puchMsg++);
if(input_invert)//输入值反转
{
quint8 temp_char = wChar;
wChar=0;
for(int i=0;i<8;++i)
{
if(temp_char&0x01)
wChar|=0x01<<(7-i);
temp_char>>=1;
}
}
wCRCin ^= (wChar << 8);
for (int i = 0; i < 8; i++)
{
if (wCRCin & 0x8000)
wCRCin = (wCRCin << 1) ^ wCPoly;
else
wCRCin = wCRCin << 1;
}
}
if(ouput_invert)
{
quint16 temp_short = wCRCin;
wCRCin=0;
for(int i=0;i<16;++i)
{
if(temp_short&0x01)
wCRCin|=0x01<<(15-i);
temp_short>>=1;
}
}
return (wCRCin^wResultXOR);
}