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;
}
运行结果:
【modbus协议CRC16校验函数】
文章图片
推荐阅读
- (八)签协议
- 计算机网络|计算机网络——DHCP协议详解
- javaEmail一(传输协议简介)
- SDP协议
- FTP创建
- Scheme跳转协议
- 开源生态|GPL、MIT、Apache...开发者如何选择开源协议(一文讲清根本区别)
- 计算机网络之ARP协议
- TCP|TCP 协议如何保证可靠传输
- TCP协议之校验和