Search code examples
cchecksumcrccrc16

How do CRC algorithms work for CCITT16 and how to get one for CCITT8


I'm looking to implement a CRC-8 checksum - and in reading up on CRC in general I came across this algorithm for CCITT-16 (polynomial X^16 + X^12 + X^5 + 1):

unsigned char ser_data;
static unsigned int crc;

crc  = (unsigned char)(crc >> 8) | (crc << 8);
crc ^= ser_data;
crc ^= (unsigned char)(crc & 0xff) >> 4;
crc ^= (crc << 8) << 4;
crc ^= ((crc & 0xff) << 4) << 1;

Alternatively as a macro:

#define crc16(chk, byte)                                   \
        {                                                  \
          chk = (unsigned char) (chk >> 8) | (chk << 8);   \
          chk ^= byte;                                     \
          chk ^= (unsigned char)(chk & 0xFF) >> 4;         \
          chk ^= (chk << 8) << 4;                          \
          chk ^= ((chk & 0xFF) << 4) << 1;                 \
        }

I have two questions here:

  1. How is this algorithm derived from the polynomial?
  2. Is there a similar simple algorithm for CCITT8 (polynomial X^8 + X^2 + X + 1)?

Solution

  • See this Painless Guide to CRC Error Detection Algorithms