C中的CRC计算

问题描述 投票:1回答:1

我有一个设备,它通过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。我认为代码中存在错误。

c crc
1个回答
1
投票

您使用的是哪个编译器/平台?你确定int数据类型是32位吗?尝试使用long并比较结果。

此外,如果出现以下情况,您可以进行以下操作:

if ( crc & 0x10000 )

在评论中,您声明您正在验证第15位。不,那不是真的,你将验证第16位。在15日,它将是( crc & 0x8000 )

© www.soinside.com 2019 - 2024. All rights reserved.