---
title: "Error detection and correction: CRCs, Hamming codes and convolutional codes"
heading: Catching corrupted frames with a cyclic redundancy check, correcting single errors with the Hamming (7,4) code and its syndrome, minimum distance and what it buys, convolutional codes with Viterbi decoding, and comparing coded and uncoded links at the same energy per bit
eyebrow: D12 · Lesson 12 · Error control
xp: 40
---

::: hook
However good the receiver, noise will sometimes flip a bit. A link has two defenses. **Detection** adds a checksum so the receiver knows a frame is damaged and can ask for it again; the CRC on every Ethernet frame, USB packet and Wi-Fi frame does this. **Correction** adds enough structured redundancy that the receiver can work out which bits were flipped and fix them on the spot, which matters when there's no time or no way to ask again: space probes, broadcast, storage.
:::

::: play
- The chance that a 4-bit word arrives wrong over BPSK, sent plainly or as a Hamming (7,4) codeword that corrects any single error, against $E_b/N_0$.
- The code spends 7 channel bits per 4 data bits, so each channel bit gets only 4/7 of the energy and is more often wrong. Correction more than makes up for it once the SNR is moderate.
- At 10 dB the coded word error rate is 5.6 times lower; at low SNR the two meet, since too many bits are wrong for one correction to help.
:::

```sim plot
view: graph
x: e = 0..12
y: P = 1e-7..1 log
plot: 1 - (1 - Q(sqrt(2*10^(e/10))))^4 | samples: 400 | label: uncoded 4-bit word (Eb/N0 in dB)
plot: 1 - (1 - Q(sqrt(8/7*10^(e/10))))^7 - 7*Q(sqrt(8/7*10^(e/10)))*(1 - Q(sqrt(8/7*10^(e/10))))^6 | samples: 400 | color: ch3 | label: Hamming (7,4), single errors corrected
```

::: predict
## A frame is corrupted by a long burst of random errors. What's the chance its 16-bit CRC still checks out?

- [ ] 1 in 16
- [ ] 1 in 256
- [x] 1 in 65,536
- [ ] Zero

::: reveal
A badly scrambled frame leaves a remainder that's effectively random, and only one of the $2^{16}$ = 65,536 possible remainders is the right one. Some error patterns are always caught: any single burst no longer than 16 bits, any single or double bit error in reasonable lengths, and any odd number of errors for many polynomials.
:::
:::

::: nameit
## The CRC

Treat the message bits as a polynomial and divide it by a generator polynomial in arithmetic modulo 2 (XOR without carries); the remainder is the **CRC**. CRC-16/CCITT uses $x^{16} + x^{12} + x^5 + 1$ (0x1021). In software it's a 16-bit shift register: XOR each byte into the top, then shift eight times, XORing in 0x1021 whenever a 1 falls off. The receiver runs the same register over the message and the CRC together and expects 0.

## Hamming codes

Three parity bits protect four data bits, each covering a different subset, so every single-bit error upsets a different combination of checks. The three failed checks, read as a binary number, the **syndrome**, are the position of the flipped bit.

## Distance

The **minimum distance** d of a code is the fewest bits in which two codewords differ. It detects up to d − 1 errors, or corrects up to ⌊(d − 1)/2⌋. Hamming (7,4) has d = 3: it corrects 1, or detects 2.

## Convolutional codes

A convolutional encoder slides a short shift register over the bit stream and sends two parity bits per input bit (rate 1/2). The classic K = 3 code with generators 111 and 101 turns 1, 0, 1, 1 into 11 10 00 01. Its **free distance** is 5. The **Viterbi** algorithm decodes it by tracking, for each of the 4 register states, the most likely path into it, and it works naturally with soft decisions, using the received analog values along with their signs. The asymptotic coding gain is $10\log_{10}(Rd_\text{free})$: 4.0 dB for this code, 7.0 dB for the K = 7 code (d = 10) used in Wi-Fi and by deep-space probes. Modern links use turbo, LDPC and polar codes, which come within a decibel of Shannon's limit.
:::

::: example
## A link's channel bits are wrong with probability 0.01. How often is a 4-bit word wrong, sent plainly and with Hamming (7,4)?

::: solution
1. **Sent plainly.** Any of the 4 bits wrong spoils the word:
   $$\begin{aligned} P &= 1 - 0.99^4 \\ &= 3.9\% \end{aligned}$$
2. **With Hamming (7,4).** A word fails only with two or more errors among 7:
   $$\begin{aligned} P &= 1 - 0.99^7 \\ &\quad - 7(0.01)(0.99)^6 \\ &= 0.20\% \end{aligned}$$
3. **Compare.** That's about 19 times better.
4. **The catch.** At the same energy per bit the coded bits are noisier, so the real gain is smaller, as the sim shows.

**Answer:** 3.9% of words are wrong sent plainly, and 0.20% with Hamming (7,4).
:::
:::

::: example
## What CRC does CRC-16/CCITT-FALSE give for the ASCII string 123456789?

::: solution
1. **Run the CRC over the nine bytes.** It gives 0x29B1, the standard check value that every implementation is tested against.
2. **Check the residue.** Appending it as the bytes 0x29, 0xB1 and running the CRC over all 11 bytes gives 0.

**Answer:** 0x29B1.
:::
:::

::: example
## A link delivers 1000 frames a second, and one in a hundred has errors. How often does CRC-16 let a bad frame through?

::: solution
1. **Bad frames per second.**
   $$1000 \times 0.01 = 10$$
2. **Time between undetected errors.** Each bad frame is undetected with probability about $2^{-16} = 1.5 \times 10^{-5}$:
   $$\begin{aligned} t &= \frac{2^{16}}{10}\ \text{s} \\ &\approx 6600\ \text{s} \\ &\approx 1.8\ \text{hours} \end{aligned}$$
3. **With a 32-bit CRC.**
   $$\begin{aligned} t &= \frac{2^{32}}{10}\ \text{s} \\ &\approx 4.3 \times 10^{8}\ \text{s} \\ &\approx 14\ \text{years} \end{aligned}$$
   That's why fast links use CRC-32.

**Answer:** one undetected error every 6600 s or so, about 1.8 hours; a CRC-32 stretches that to about 14 years.
:::
:::

::: check
kind: python

## Write a CRC-16 and a Hamming (7,4) encoder and decoder.

```python starter
def crc16(data):
    # CRC-16/CCITT-FALSE over a bytes object: polynomial 0x1021, register starting at 0xFFFF,
    # each byte fed in most significant bit first, no final XOR. For each byte: XOR it into the
    # register's top 8 bits, then 8 times: shift left one bit and, if a 1 fell off the top,
    # XOR in 0x1021. Keep the register to 16 bits.
    return 0

def hamming74_encode(d):
    # Four data bits d1..d4 to the codeword [p1, p2, d1, p3, d2, d3, d4], with
    # p1 = d1^d2^d4, p2 = d1^d3^d4, p3 = d2^d3^d4.
    return [0]*7

def hamming74_decode(c):
    # Recompute the three checks: s1 = c1^c3^c5^c7, s2 = c2^c3^c6^c7, s3 = c4^c5^c6^c7
    # (positions counted from 1). The syndrome s1 + 2*s2 + 4*s3 is the position of a single
    # flipped bit (0 for none). Flip it back and return the data bits [c3, c5, c6, c7].
    return [0]*4
```

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

def hamming74_encode(d):
    d1, d2, d3, d4 = d
    return [d1 ^ d2 ^ d4, d1 ^ d3 ^ d4, d1, d2 ^ d3 ^ d4, d2, d3, d4]

def hamming74_decode(c):
    c = list(c)
    s1 = c[0] ^ c[2] ^ c[4] ^ c[6]
    s2 = c[1] ^ c[2] ^ c[5] ^ c[6]
    s3 = c[3] ^ c[4] ^ c[5] ^ c[6]
    pos = s1 + 2*s2 + 4*s3
    if pos:
        c[pos - 1] ^= 1
    return [c[2], c[4], c[5], c[6]]
```

```python tests
assert crc16(b"123456789") == 0x29B1, f"The standard check value of CRC-16/CCITT-FALSE for '123456789' is 0x29B1; got {crc16(b'123456789'):#06x}."
_m = b"Ohmwork modem"
_c = crc16(_m)
assert crc16(_m + bytes([_c >> 8, _c & 0xFF])) == 0, "A message followed by its own CRC leaves a remainder of 0: that's how the receiver checks it."
_bad = bytearray(_m); _bad[3] ^= 0x10
assert crc16(bytes(_bad)) != _c, "A flipped bit changes the CRC."
assert hamming74_encode([1, 0, 1, 1]) == [0, 1, 1, 0, 0, 1, 1], f"1011 encodes to 0110011; got {hamming74_encode([1, 0, 1, 1])}."
_words = [[(v >> 3) & 1, (v >> 2) & 1, (v >> 1) & 1, v & 1] for v in range(16)]
_codes = [hamming74_encode(w) for w in _words]
assert min(sum(a != b for a, b in zip(x, y)) for i, x in enumerate(_codes) for y in _codes[i + 1:]) == 3, "Any two codewords differ in at least 3 places."
for _w, _cw in zip(_words, _codes):
    assert hamming74_decode(_cw) == _w, "An undamaged codeword decodes to its data."
    for _k in range(7):
        _e = list(_cw); _e[_k] ^= 1
        assert hamming74_decode(_e) == _w, f"A single flipped bit (position {_k + 1}) must be corrected."
```

::: right
Right. Your CRC matches the standard check value and catches damage, and your Hamming decoder corrects every single-bit error in every codeword.
:::
:::

::: check
given: p = 0.001 | 0.003 | 0.01 | 0.03
answer: 1 - (1 - p)^7 - 7*p*(1 - p)^6
tolerance: 0.5%

## Channel bits are wrong with probability {p}. How often does a Hamming (7,4) word fail to decode correctly?

::: right
Right. Two or more errors in 7: {answer}.
:::

::: misses
- [1 - (1 - p)^4] That's an uncoded 4-bit word.
- [1 - (1 - p)^7] The code corrects one error; only two or more cause a failure.
- [any] Not yet. One minus the chance of zero or one error.
:::
:::

::: check
given: R = 0.5 | 0.333 | 0.75; d = 5 | 7 | 10
answer: 10*log(R*d)
unit: dB
tolerance: 0.5%

## A code of rate {R} has free distance {d}. What's its asymptotic coding gain?

::: right
Right. $10\log_{10}(Rd)$ = {answer} dB.
:::

::: misses
- [10*log(d)] Each coded bit carries only R of the energy.
- [any] Not yet. Rate times distance.
:::
:::

::: check
given: d = 3 | 5 | 7 | 9 | 11
answer: (d - 1)/2
tolerance: 0.4

## A code's minimum distance is {d}. How many bit errors per word can it always correct?

::: right
Right. ⌊(d − 1)/2⌋ = {answer}.
:::

::: misses
- [d - 1] That's how many it can detect.
- [any] Not yet. Corrections need the damaged word to stay closer to the original than to any other.
:::
:::

::: check
given: n = 8 | 16 | 24 | 32
answer: 2^(-n)
tolerance: 0.5%

## What fraction of badly corrupted frames, with effectively random remainders, does an {n}-bit CRC fail to catch?

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

::: misses
- [1/n] Only one of the $2^n$ possible remainders matches.
- [any] Not yet. One remainder out of all the possible ones.
:::
:::

::: check
kind: parts
given: p = 0.001 | 0.01 | 0.05; n = 4 | 8

## Channel bits are wrong with probability {p}. {n}-bit words are sent plainly.

::: part
answer: (1 - (1 - p)^n)*100
unit: %
tolerance: 0.5%

### How often is a word wrong?

::: misses
- [any] $1 - (1 - p)^n$.
:::
:::

::: part
answer: (1 - (1 - p)^7 - 7*p*(1 - p)^6)*100
unit: %
tolerance: 0.5%

### How often does a Hamming (7,4) word fail?

::: misses
- [any] Two or more errors among 7.
:::
:::
:::

::: check
kind: parts
given: f = 100 | 1000; e = 0.1 | 1 | 10; k = 16 | 32

## A link delivers {f} frames a second, {e}% of them with errors, checked by a {k}-bit CRC.

::: part
answer: f*e/100*2^(-k)
tolerance: 0.5%

### How many bad frames slip through per second?

::: misses
- [any] Bad frames × $2^{-k}$.
:::
:::

::: part
answer: 1/(f*e/100*2^(-k))/3600
unit: h
tolerance: 0.5%

### On average, how many hours between them?

::: misses
- [any] The reciprocal, in hours.
:::
:::
:::

::: explain
## How does a Hamming code know which bit to correct?

::: model
Each of the three parity bits checks a different group of positions, chosen so that every position belongs to a different combination of groups. When one bit flips, exactly the checks covering that position fail, and that pattern of failures is unique to it. Reading the three pass-or-fail results as a binary number gives the syndrome, which directly names the position of the flipped bit, so the decoder flips it back. If two bits flip, the syndrome points to a third position instead, which is why the code can only correct single errors.
:::
:::

::: practice

::: check
given: p = 0.0001 | 0.001 | 0.005 | 0.01 | 0.02 | 0.05 | 0.1
answer: 1 - (1 - p)^7 - 7*p*(1 - p)^6
tolerance: 0.5%

## Hamming (7,4) word failure at p = {p}?

::: misses
- [any] Two or more of seven.
:::
:::

::: check
given: R = 0.25 | 0.5 | 0.875; d = 5 | 6 | 15
answer: 10*log(R*d)
unit: dB
tolerance: 0.5%

## Coding gain: rate {R}, distance {d}?

::: misses
- [any] $10\log_{10}(Rd)$.
:::
:::
:::
