简体   繁体   中英

CRC Calculation in C

I have a device, which sends me Data with CRC Calculation. Every 16 Bytes there are 2 CRC Bytes. The generator polynomial is 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. 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? Try it with long and compare the results.

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. No, that's not true, you will be verifying the 16th bit. For the 15th it would be ( crc & 0x8000 ) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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