简体   繁体   English

C中的CRC计算

[英]CRC Calculation in C

I have a device, which sends me Data with CRC Calculation. 我有一台设备,可以通过CRC计算向我发送数据。 Every 16 Bytes there are 2 CRC Bytes. 每16个字节就有2个CRC字节。 The generator polynomial is x16 + x13 + x12 + x11 + x10 + x8 + x6 + x5 + x2 + 1 生成多项式为x16 + x13 + x12 + x11 + x10 + x8 + x6 + x5 + x2 + 1

My code looks like this: 我的代码如下所示:

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 */
}

I've also tried this code with other polynomials like 0x9CB2. 我还尝试了使用其他多项式(例如0x9CB2)编写此代码。 I think there's an error located in the code. 我认为代码中存在错误。

Which compiler/platform are you using? 您正在使用哪个编译器/平台? Are you sure the int datatype is 32 bits? 您确定int数据类型是32位吗? Try it with long and compare the results. long尝试并比较结果。

Also, there is a point in which you make the following if: 另外,在以下情况下,您需要进行以下操作:

if ( crc & 0x10000 )

and in the comment you state that you are verifying the 15th bit. 并在注释中指出要验证第15位。 No, that's not true, you will be verifying the 16th bit. 不,那不是真的,您将验证第16位。 For the 15th it would be ( crc & 0x8000 ) . 对于15号,它将是( crc & 0x8000 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM