我有一个设备,它向我发送带有 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)尝试了这段代码。我认为代码中存在错误。