Try Embedded

Checksums and CRCs

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

Knowing that data is still good

Bits go wrong. A flash cell loses charge, a power cut interrupts a write, noise flips a bit on a UART cable. Firmware cannot prevent every corruption, but it must detect it before acting on bad data: a corrupted calibration value or motor setpoint is worse than none. The tool for that is a check value stored or sent with the data, and in embedded systems that almost always means a CRC.

From sums to CRCs

CheckHowCatchesMisses
Parity bitXOR of all bitsAny single flipped bitAny two flipped bits
Simple sum (8-bit)Add all bytesMost single-byte errorsSwapped bytes, a +1 in one byte and −1 in another
Fletcher / AdlerTwo running sums, the second over the firstAlso byte orderSome patterns; weak on short data
CRCRemainder of polynomial divisionAll single-bit errors, double-bit errors up to a long message length, all bursts up to its widthVery little, for its size

A sum treats {0x12, 0x34} and {0x34, 0x12} as the same. A CRC does not, because each bit's effect depends on its position.

How a CRC works

Treat the message as one long binary number and divide it by a fixed polynomial, using XOR instead of subtraction (no carries). The remainder is the CRC. In code that is a shift register: shift each bit in, and whenever a 1 falls off the top, XOR the polynomial in.

#include <stdio.h>
#include <stdint.h>
#include <string.h>

/* CRC-16/CCITT-FALSE: polynomial 0x1021, initial value 0xFFFF, MSB first. */
static uint16_t crc16_ccitt(const uint8_t *data, size_t len) {
  uint16_t crc = 0xFFFF;
  for (size_t i = 0; i < len; i++) {
    crc ^= (uint16_t)(data[i] << 8);            /* bring the next byte into the top */
    for (int bit = 0; bit < 8; bit++) {
      if (crc & 0x8000) crc = (uint16_t)((crc << 1) ^ 0x1021);   /* a 1 falls off: subtract (XOR) */
      else              crc = (uint16_t)(crc << 1);
    }
  }
  return crc;
}

/* The same idea with the 8-bit sum, for comparison. */
static uint8_t sum8(const uint8_t *data, size_t len) {
  uint8_t s = 0;
  for (size_t i = 0; i < len; i++) s += data[i];
  return s;
}

int main(void) {
  const char *check = "123456789";               /* the standard test string */
  printf("CRC of \"123456789\" = 0x%04X (the published check value is 0x29B1)\n",
         crc16_ccitt((const uint8_t *)check, strlen(check)));

  uint8_t a[] = { 0x12, 0x34, 0x56 };
  uint8_t b[] = { 0x34, 0x12, 0x56 };            /* two bytes swapped */
  printf("sum:  a=0x%02X  b=0x%02X  -> %s\n", sum8(a, 3), sum8(b, 3),
         sum8(a, 3) == sum8(b, 3) ? "swap NOT detected" : "detected");
  printf("crc:  a=0x%04X  b=0x%04X  -> %s\n", crc16_ccitt(a, 3), crc16_ccitt(b, 3),
         crc16_ccitt(a, 3) == crc16_ccitt(b, 3) ? "swap NOT detected" : "detected");
  return 0;
}

Every check value is published: the CRC of the ASCII string 123456789. Always test your implementation against it: a CRC with one parameter wrong still produces plausible-looking numbers.

The parameters

"CRC-16" is not one algorithm. A CRC is fully defined by:

ParameterMeaningExample (CRC-32, as in Ethernet and zip)
WidthBits in the result32
PolyThe divisor0x04C11DB7
InitStarting register value0xFFFFFFFF
RefIn / RefOutProcess bits LSB first? Reflect the result?true / true
XorOutXOR applied at the end0xFFFFFFFF
CheckCRC of "123456789"0xCBF43926

When two devices disagree on CRCs, one of these differs. A non-zero init matters: with init 0, leading zero bytes do not change the CRC, so a message gaining extra zeros at the front goes unnoticed.

Faster: a lookup table

The bit loop costs 8 iterations per byte. A 256-entry table precomputes the effect of each possible byte, so each byte needs one lookup, one shift and one XOR. That is 512 bytes of flash for CRC-16 or 1 KB for CRC-32. A 16-entry, nibble-at-a-time table is a good middle ground for small parts, and many microcontrollers have a hardware CRC unit, often fed by DMA, which is faster still. Check its parameters: STM32's default unit computes CRC-32 with the polynomial above, but without reflection or final XOR.

Using CRCs on stored data

A record in flash or EEPROM should carry enough to prove it is complete and current:

typedef struct {
  uint16_t magic;      /* 0xC0F1: this is a settings record at all */
  uint16_t version;    /* layout version, so new firmware can migrate old records */
  uint32_t sequence;   /* incremented on each save: the highest valid one wins */
  settings_t data;
  uint32_t crc;        /* CRC-32 over everything above; written last */
} record_t;

On boot, check the magic, then the CRC, and only then trust the version and data. If no record is valid, fall back to compiled-in defaults and report it. Writing the CRC last means a power cut mid-write leaves a record that fails the check rather than one that looks valid.

Pitfall: Computing the CRC over a struct includes its padding bytes, whose values are undefined. Zero the struct with memset before filling it, or compute the CRC over a packed byte buffer.

Interview question: How would you protect configuration data stored in flash against corruption?

Answer: Each record gets a magic number, a layout version, a sequence number and a CRC-32 over everything, with the CRC written last. I keep two slots and write alternately, so a power cut during a write damages only the slot being written. On boot I check the magic and CRC of both slots and use the valid one with the highest sequence number; if neither is valid, I load compiled-in defaults and log the event. The version lets newer firmware migrate an older layout instead of rejecting it.

Build it: two copies of the settings, and the right one at boot

This is step 4, the last of the module project. The recorder's calibration (sensor offsets, the drone's serial number, the log rate) must never be lost, not even if the power fails while it is being updated. The standard answer is two slots, A and B: write the new settings over the older slot, and at boot take the newest slot whose CRC is correct.

Lab: Pick the newest valid settings slot with CRC-32

Each slot is 16 bytes: a 32-bit sequence number, 8 bytes of settings, then a CRC-32 of the first 12 bytes. All numbers are stored low byte first. Each save writes sequence + 1 into the slot that was not picked at the last boot, so a power cut damages at most the slot being written, and the other still holds the previous settings.

The CRC is the common CRC-32 (as in Ethernet and ZIP): start at 0xFFFFFFFF; for each byte, XOR it into the low 8 bits, then 8 times shift right one bit, XOR-ing in 0xEDB88320 whenever the bit shifted out was 1; at the end invert all the bits.

  • crc32(data, n) computes it. The check value: "123456789" gives 0xCBF43926.
  • slot_build(seq, cfg, out) fills the 16 bytes of a slot.
  • config_pick(a, b, out) checks both slots. If both are valid it takes the one with the newer sequence number. Sequence numbers wrap around after 0xFFFFFFFF, so compare them the wrap-safe way: a is newer than b when (int32_t)(a - b) > 0. It copies the chosen settings to out and returns 0 for slot A or 1 for slot B. If neither is valid it returns -1 and leaves out alone.

Going deeper

Interview question: How would you store a greenhouse controller's settings so a power cut never corrupts them?

Answer: Keep two copies (A and B) of a record with a version, a sequence number and a CRC. Write the older copy, then check it; at boot, use the newest copy whose CRC checks out. A power cut during a write leaves the other copy intact, and a version number lets a firmware update migrate old records instead of misreading them.

Interview question: Why does a CRC detect burst errors so well?

Answer: A CRC of width n is the remainder after dividing by a polynomial of degree n. A burst error of length n or less corresponds to an error polynomial that the generator cannot divide evenly, as long as the polynomial has a non-zero constant term, so it always leaves a non-zero change in the remainder. Longer bursts are still caught with a probability of about 1 − 2^−n. That matches real channels, where noise tends to corrupt several neighbouring bits.

Interview question: Is a CRC enough to protect a firmware image from tampering?

Answer: No. A CRC detects accidental corruption, but it is not secret and is easy to recompute, so an attacker who modifies the image simply updates the CRC too. Protecting against tampering needs a cryptographic signature, for example ECDSA over a SHA-256 hash, verified with a public key the device trusts. A CRC is still useful alongside it as a fast check for transfer errors.

Explain it: In your own words, explain how a CRC is computed and why it is better than a simple checksum.

Answer: The message is treated as a long binary number and divided by a fixed polynomial using XOR instead of subtraction; the remainder is the CRC. In code this is a shift register: each bit is shifted in, and when a 1 falls off the top, the polynomial is XORed in. A simple checksum just adds the bytes, so it cannot see bytes in the wrong order or errors that cancel out. Because every bit's effect on a CRC depends on its position, a well-chosen CRC catches all single-bit errors, double-bit errors in messages up to a designed length, and all bursts up to its width.