modbus协议CRC16校验函数

CRC函数:

unsigned short CheckCRC(unsigned char *pData,unsigned int siLen)
{
	if (NULL == pData || siLen <= 0)
	{
		return 0;
	}
	
	unsigned short u16CRC = 0xFFFF;
	for (int i = 0; i < siLen; i++)
	{
		u16CRC ^= (unsigned short)(pData[i]);
		for(int j = 0; j <= 7; j++)
		{
			if (u16CRC & 0x0001)
			{
				u16CRC = (u16CRC >> 1) ^ 0xA001;
			}
			else
			{
				u16CRC = u16CRC >> 1;  
			}
		}
	}

	unsigned short siRet = 0;
	siRet = (u16CRC & 0x00FF) << 8; 
	siRet |= u16CRC >> 8;
	
	return siRet;
}


实例:

int main()
{
	unsigned char data[] = {0x55,0xFE,0xFE,0x03,0x05,0x01};
	unsigned short CRC = CheckCRC(data, sizeof(data));
	
	printf("CRC = %x \r\n", CRC);
	
	return 0;
}

运行结果:


你可能感兴趣的:(协议)