Simvik

Fix: our CRC matches the wrong tool

A CRC-16 routine has the right polynomial and the wrong initial value. A medium embedded C problem (Checksums and CRCs), run and graded in the browser.

medium · Checksums and CRCs · find-the-bug · crc · parameters

Bug report. The bootloader protects each block with CRC-16/CCITT-FALSE: polynomial 0x1021, initial value 0xFFFF, no reflection, no final XOR. Its check value, the CRC of the ASCII string 123456789, is 0x29B1. Our crc16 gives 0x31C3 for that string, which matches the XMODEM variant instead, so the bootloader rejects every block. Fix it by changing one line.

Starter code

uint16_t crc16(const uint8_t *d, size_t n) {
  uint16_t crc = 0x0000;
  for (size_t i = 0; i < n; i++) {
    crc ^= (uint16_t)(d[i] << 8);
    for (int b = 0; b < 8; b++)
      crc = (crc & 0x8000) ? (uint16_t)((crc << 1) ^ 0x1021) : (uint16_t)(crc << 1);
  }
  return crc;
}

Example tests

The check value

printf("0x%04X\n", crc16((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