---
title: "Project: CRC error checking"
heading: Protecting a data link with a shift register and a lookup table
eyebrow: C7 · Lesson 55 · Project
xp: 80
---

::: hook
A temperature sensor sends readings over a long cable to a microcontroller, and every so often a burst of noise flips a bit. The fix used on the sensor's bus, as on Ethernet, USB and every disk, is a cyclic redundancy check: the sender divides its message by a fixed polynomial and appends the remainder, and the receiver repeats the division to see whether anything changed. In this project you'll watch the hardware version run in a 3-bit shift register, then implement the standard 8-bit CRC two ways in Python, bit by bit as the hardware does it and a byte at a time with a lookup table, and verify both against the published check values.
:::

::: play
- A serial CRC register for the generator $x^3 + x + 1$ (1011). The message 1101 enters one bit per clock on D; EN stops the register after the fourth bit.
- Each clock, the top bit $Q_2$ XORed with the incoming bit is fed back into the positions where the generator has terms ($x^1$ and $x^0$).
- After four clocks $Q_2Q_1Q_0$ = 001: the remainder of lesson 31's long division, computed with three flip-flops and two XOR gates.
:::
:::

```sim logic
clock CLK 8
input D, EN
output Q2, Q1, Q0
stim D 1@0 0@14 1@22 0@30
stim EN 1@0 0@30
always @(posedge CLK) begin
  Q0 <= EN ? (Q2 ^ D) : Q0;
  Q1 <= EN ? (Q0 ^ Q2 ^ D) : Q1;
  Q2 <= EN ? Q1 : Q2;
end
wave: CLK, D, EN, Q2, Q1, Q0
time: 48
```

::: predict
## The sender appends a message's CRC to it. What does the receiver get when it computes the CRC of the message plus that appended CRC, if nothing was corrupted?

- [ ] The same CRC again
- [x] Zero
- [ ] All ones
- [ ] The message

::: reveal
Zero. Appending the remainder makes the whole frame exactly divisible by the generator, so dividing it again leaves nothing. Any single error, any two errors, and any burst shorter than the CRC change the remainder, so a nonzero result means corruption.
:::
:::

::: nameit
## The bitwise CRC

The hardware register, in software: keep an n-bit value c (starting from an initial value, often 0). For each data byte, XOR it into the top of c; then, for each of its 8 bits, shift c left one place, and if the bit shifted out was 1, XOR in the generator polynomial (written without its top term: $x^8 + x^2 + x + 1$ is 0x07).

## The table-driven CRC

The 8 shift-and-XOR steps for a byte depend only on the 8 bits involved, so precompute them once for all 256 possible values: `table[i]` is the CRC of the single byte i. Then each byte costs one lookup:

$$c \leftarrow \text{table}[c \oplus \text{byte}]$$

for an 8-bit CRC (wider CRCs shift c and XOR in the table entry). That's eight times fewer steps, and it's how CRCs run in software.

## Standard CRCs

A CRC is fully specified by its width, generator, initial value and a few bit-order options, and each standard publishes a **check value**: the CRC of the ASCII string "123456789".

| Name | Width | Generator | Initial | Check |
|---|---|---|---|---|
| CRC-8 (SMBus) | 8 | 0x07 | 0x00 | 0xF4 |
| CRC-16 (CCITT-FALSE) | 16 | 0x1021 | 0xFFFF | 0x29B1 |

An n-bit CRC detects every error burst of n bits or fewer, and misses a random corruption with probability $2^{-n}$.
:::

::: example
## Step the serial CRC register through the message 1101.

::: solution
1. **Set up.** Start at 000; each clock, the feedback is $f = Q_2 \oplus D$, then $Q_2 \leftarrow Q_1$, $Q_1 \leftarrow Q_0 \oplus f$, $Q_0 \leftarrow f$.
2. **Clock in the message.**

| D | f | $Q_2Q_1Q_0$ |
|---|---|---|
| 1 | 1 | 011 |
| 1 | 1 | 101 |
| 0 | 1 | 001 |
| 1 | 1 | 001 |

3. **Read the remainder.** The remainder is 001.

**Answer:** the remainder is 001.
:::
:::

::: example
## What is `table[1]` for CRC-8 with generator 0x07?

::: solution
1. **Shift seven times.** The byte 00000001 shifts left seven times without anything falling out, reaching 10000000.
2. **The eighth shift.** It drops that 1 and XORs in 0x07, so `table[1]` = 0x07.
3. **In general.** `table[i]` is the remainder of $i \cdot x^8$.

**Answer:** `table[1]` = 0x07.
:::
:::

::: check
given: n = 8 | 16 | 32
answer: n
tolerance: 0

## What is the longest error burst a CRC with an {n}-bit remainder is guaranteed to detect?

::: right
Right. {answer} bits.
:::

::: misses
- [2^n] That's the number of possible remainders, not the burst length.
- [any] Not yet. Any burst no longer than the CRC.
:::
:::

::: check
given: n = 8 | 16 | 32
answer: -n*log(2)/log(10)
tolerance: 0.5%

## For random corruption, an {n}-bit CRC misses an error with probability $2^{-n}$. What is that as a power of ten (the exponent)?

::: right
Right. $\log_{10}2^{-n}$ = {answer}.
:::

::: misses
- [any] Not yet. $-n\log_{10}2$.
:::
:::

::: check
kind: python

## Write `crc8(data, poly=0x07, init=0x00)` for a `bytes` object, bitwise, and check it gives 0xF4 for `b"123456789"`.

```python starter
def crc8(data, poly=0x07, init=0x00):
    c = init
    for b in data:
        c = (c + b) & 0xFF
    return c
```

```python solution
def crc8(data, poly=0x07, init=0x00):
    c = init
    for b in data:
        c ^= b
        for _ in range(8):
            if c & 0x80:
                c = ((c << 1) ^ poly) & 0xFF
            else:
                c = (c << 1) & 0xFF
    return c
```

```python tests
assert crc8(b"123456789") == 0xF4, f"The CRC-8 check value is 0xF4; got {crc8(b'123456789'):#04x}."
assert crc8(b"hello") == 0x92, f"crc8(b'hello') should be 0x92; got {crc8(b'hello'):#04x}."
m = b"temperature 21.5"
assert crc8(m + bytes([crc8(m)])) == 0, "A message with its CRC appended should give 0."
assert crc8(b"A") != crc8(b"C"), "A one-bit change must change the CRC."
```

::: right
Right. The starter's checksum, a plain sum, would miss two errors that cancel, like a bit set in one byte and cleared at the same place in another; the CRC catches them.
:::
:::

::: check
kind: python

## Write `make_table(poly=0x07)` returning the 256-entry CRC-8 table, and `crc8_fast(data, table, init=0x00)` that uses one lookup per byte.

```python starter
def make_table(poly=0x07):
    return list(range(256))

def crc8_fast(data, table, init=0x00):
    c = init
    for b in data:
        c = table[b]
    return c
```

```python solution
def make_table(poly=0x07):
    table = []
    for i in range(256):
        c = i
        for _ in range(8):
            c = ((c << 1) ^ poly) & 0xFF if c & 0x80 else (c << 1) & 0xFF
        table.append(c)
    return table

def crc8_fast(data, table, init=0x00):
    c = init
    for b in data:
        c = table[c ^ b]
    return c
```

```python tests
import random
t = make_table()
assert len(t) == 256 and t[0] == 0 and t[1] == 0x07 and t[255] == 0xF3, f"Expected table[1] = 0x07 and table[255] = 0xF3; got {t[1]:#04x}, {t[255]:#04x}."
assert crc8_fast(b"123456789", t) == 0xF4, "The fast CRC must give the same check value, 0xF4."
random.seed(7)
for _ in range(50):
    d = bytes(random.randrange(256) for _ in range(random.randrange(1, 40)))
    c = 0
    for b in d:
        c ^= b
        for _ in range(8):
            c = ((c << 1) ^ 0x07) & 0xFF if c & 0x80 else (c << 1) & 0xFF
    assert crc8_fast(d, t) == c, "The table-driven CRC must match the bitwise one on every message."
```

::: right
Right. One lookup per byte instead of eight shifts: the standard software method.
:::
:::

::: check
kind: python

## Write `crc16_ccitt(data)`: the 16-bit CRC with generator 0x1021 and initial value 0xFFFF, bitwise, which gives 0x29B1 for `b"123456789"`.

```python starter
def crc16_ccitt(data):
    c = 0xFFFF
    for b in data:
        c ^= b
    return c
```

```python solution
def crc16_ccitt(data):
    c = 0xFFFF
    for b in data:
        c ^= b << 8
        for _ in range(8):
            if c & 0x8000:
                c = ((c << 1) ^ 0x1021) & 0xFFFF
            else:
                c = (c << 1) & 0xFFFF
    return c
```

```python tests
assert crc16_ccitt(b"123456789") == 0x29B1, f"The check value is 0x29B1; got {crc16_ccitt(b'123456789'):#06x}."
assert crc16_ccitt(b"hello") == 0xD26E, f"crc16_ccitt(b'hello') should be 0xD26E; got {crc16_ccitt(b'hello'):#06x}."
assert crc16_ccitt(b"") == 0xFFFF, "With no data the CRC is the initial value."
```

::: right
Right. The only changes from CRC-8 are the width, the generator and where each byte enters: at the top of the 16-bit register.
:::
:::

::: explain
## Why does a CRC catch errors that a simple sum of the bytes would miss?

::: model
A sum only accumulates the bytes' values, so many different corruptions leave it unchanged: two errors that cancel arithmetically, bytes swapped in order, or a bit set in one byte and cleared in the same place in another. A CRC is the remainder of dividing the whole message, as one long polynomial, by a carefully chosen generator, so every bit's position matters: a change anywhere shifts the remainder unless the error pattern is itself a multiple of the generator. Generators are chosen so that no short burst, and no small number of scattered bit errors, is such a multiple.
:::
:::

::: practice

::: check
given: n = 8 | 16 | 32; k = 4 | 8
answer: 2^k
tolerance: 0

## A table-driven {n}-bit CRC looks up {k} bits of the message at a time. How many entries does its table have?

::: misses
- [any] One entry for each possible value of the {k} bits it looks up. The CRC's width only sets how wide each entry is.
:::
:::

::: check
given: L = 10 | 100 | 1500
answer: 8*L
tolerance: 0

## A bitwise CRC processes one bit per step. How many steps for a {L}-byte message?

::: misses
- [any] Eight per byte.
:::
:::

::: check
given: n = 3 | 8 | 16
answer: n
tolerance: 0

## How many flip-flops does a serial CRC register for an {n}-bit CRC use?

::: misses
- [any] One per remainder bit.
:::
:::
:::
