Simvik

A table-driven CRC-16

Build a 256-entry table once, then compute CRC-16/CCITT a byte at a time. A medium embedded C problem (Checksums and CRCs), run and graded in the browser.

medium · Checksums and CRCs · crc · lookup-table · performance

The bit-by-bit CRC loop costs eight steps per byte. A lookup table precomputes, for every possible top byte, its effect after eight steps, so each data byte takes one lookup.

For CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, not reflected, no final XOR, check 0x29B1):

  • crc16_make_table(t): entry t[i] is what eight bit steps do to the value i << 8,
  • crc16_table(t, data, len): start at 0xFFFF; for each byte, crc = (crc << 8) ^ t[(crc >> 8) ^ byte], kept to 16 bits.

Starter code

void crc16_make_table(uint16_t t[256]) {
  for (int i = 0; i < 256; i++) t[i] = (uint16_t)(i << 8);
}

uint16_t crc16_table(const uint16_t t[256], const uint8_t *data, size_t len) {
  uint16_t crc = 0xFFFF;
  for (size_t i = 0; i < len; i++) crc = (uint16_t)((crc << 8) ^ t[(crc >> 8) ^ data[i]]);
  return crc;
}

Example tests

Table entries

uint16_t t[256];
crc16_make_table(t);
printf("t[1] = 0x%04X, t[2] = 0x%04X, t[255] = 0x%04X\n", t[1], t[2], t[255]);

Expected output:

t[1] = 0x1021, t[2] = 0x2042, t[255] = 0x1EF0

The check value

uint16_t t[256];
crc16_make_table(t);
printf("0x%04X\n", crc16_table(t, (const uint8_t *)"123456789", 9));

Expected output:

0x29B1

Learn it first

  • Checksums and CRCs · Detecting corruption: sums versus CRCs, CRC parameters, tables and protecting stored records.

More Checksums and CRCs problems