[英]CRC Calculation in C
我有一台设备,可以通过CRC计算向我发送数据。 每16个字节就有2个CRC字节。 生成多项式为x16 + x13 + x12 + x11 + x10 + x8 + x6 + x5 + x2 + 1
我的代码如下所示:
int crc16(unsigned char *addr, int num, int crc)
{
uint16_t poly = 0x3D65;
int i;
for (; num > 0; num--) /* Step through bytes in memory */
{
crc = crc ^ ((unsigned short)*addr++ << 8); /* Fetch byte from memory, XOR into CRC top byte*/
for (i = 0; i < 8; i++) /* Prepare to rotate 8 bits */
{
if (crc & 0x10000) /* b15 is set... */
crc = (crc << 1) ^ poly; /* rotate and XOR with XMODEM polynomic */
else /* b15 is clear... */
crc <<= 1; /* just rotate */
} /* Loop for 8 bits */
crc &= 0xFFFF; /* Ensure CRC remains 16-bit value */
} /* Loop until num=0 */
return(crc); /* Return updated CRC */
}
我还尝试了使用其他多项式(例如0x9CB2)编写此代码。 我认为代码中存在错误。
您正在使用哪个编译器/平台? 您确定int
数据类型是32位吗? long
尝试并比较结果。
另外,在以下情况下,您需要进行以下操作:
if ( crc & 0x10000 )
并在注释中指出要验证第15位。 不,那不是真的,您将验证第16位。 对于15号,它将是( crc & 0x8000 )
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.