0
votes

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.

1
And your question is .... what, exactly? - paxdiablo
Could you elaborate more the question, please? tell us exactly where the problem is... - felixgaal
Ok, so you think there's an error in the code. But why do you think that? What exactly is it that doesn't work? Which incorrect results do you get? - Thomas Padron-McCarthy
How does the documentation of the device describe the CRC, besides the polynomial? The CRC bits could be stored in either order, there could be an initial value different from zero, and there could be pre and/or post conditioning. You should read ross.net/crc/download/crc_v3.txt . - Mark Adler
Can you provide an example of 16 bytes of data and the 2-byte crc from the device? - Mark Adler

1 Answers

1
votes

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 ).