---
title: Codes and parity
heading: Gray code, BCD, and bits that catch and correct errors
eyebrow: C7 · Lesson 3 · Codes and parity
xp: 40
---

::: hook
Plain binary is the natural way to count, but it isn't always the right way to encode. A shaft encoder read in binary can report wild values as it turns; a decimal display wants digits, not powers of two; a bit flipped by noise in a memory or on a cable should be noticed, and better, fixed. A handful of codes handle all three, and they're built from the gate you already know best for the job: XOR.

::: play
- The circuit converts a 4-bit binary number B to Gray code G and computes its parity P (1 when an odd number of bits are 1).
- Step B from 0 to 15 and watch G: exactly one bit changes at each step, even from 7 to 8, where binary changes all four.
- Watch P: it changes at every step of the Gray code, since each step flips one bit.
:::
:::

```sim logic
input B3, B2, B1, B0
output G3, G2, G1, G0, P
assign G3 = B3
assign G2 = B3 ^ B2
assign G1 = B2 ^ B1
assign G0 = B1 ^ B0
assign P = B3 ^ B2 ^ B1 ^ B0
table: on
```

::: predict
## A 3-bit position sensor reports its angle in plain binary. As it turns from 3 (011) to 4 (100), its three bits don't switch at exactly the same instant. What might a reader that samples in between see?

- [ ] Only 3 or 4
- [ ] 3, 4, or the average, 3.5
- [x] Any of the eight values, since all three bits change
- [ ] Nothing: the bits change together

::: reveal
Any value. All three bits change, and a sample taken while some have switched and others haven't can catch any combination: 000, 111, 101 and so on. A reading of 7 from a sensor moving between 3 and 4 is a serious error. In Gray code, neighbors differ in one bit, so a sample in between can only be one or the other.
:::
:::

::: nameit
## Gray code

Neighboring values differ in exactly one bit. Conversion is a shift and an XOR:

$$G = B \oplus (B \gg 1), \qquad B_{n-1} = G_{n-1},\quad B_i = B_{i+1} \oplus G_i.$$

Gray code is used for shaft and position encoders, for counters whose values cross clock domains (lesson 41), and to order Karnaugh map rows.

## BCD

**Binary-coded decimal** stores each decimal digit in 4 bits: 59 is 0101 1001. Only 10 of the 16 codes are used, an efficiency of $\frac{\log_210}{4}$ = 83%, but conversion to a display is trivial. Adding BCD digits in binary needs a correction: if a digit's sum exceeds 9, add 6 to skip the six unused codes, and carry.

## Parity

An **even parity** bit is the XOR of the data bits, so the whole word always holds an even number of 1s. Any single flipped bit, indeed any odd number, makes the parity wrong. It can't say which bit, and two errors cancel.

## Hamming codes

Placing several parity bits so that each checks a different subset of positions lets the pattern of failed checks, the **syndrome**, point at the bad bit. In the Hamming(7,4) code, with positions 1 to 7, parity bits sit at 1, 2 and 4, and parity bit $2^j$ checks every position whose number has bit j set. A single error at position p gives a syndrome equal to p. With r parity bits, k data bits can be protected if

$$2^r \ge k + r + 1.$$

The **minimum distance** d between codewords sets what a code can do: detect up to $d - 1$ errors, or correct up to $\left\lfloor\frac{d - 1}{2}\right\rfloor$. Hamming codes have d = 3; adding an overall parity bit gives d = 4, correcting one error and detecting two (SECDED), as in ECC memory.
:::

::: example
## Convert 13 to 4-bit Gray code and back.

::: solution
1. **Shift right and XOR.** 13 = 1101, and shifted right it's 0110:
   $$1101 \oplus 0110 = 1011$$
2. **Convert back.** The top bit is 1; then XOR in each Gray bit below it in turn:
   $$\begin{aligned} 1 \oplus 0 &= 1 \\ 1 \oplus 1 &= 0 \\ 0 \oplus 1 &= 1 \end{aligned}$$
   giving 1101 = 13 again.
3. **Why that works.** Each binary bit is the XOR of all the Gray bits above and including it, so the conversion back is a running XOR from the top.

**Answer:** 13 is 1011 in Gray code, and converting 1011 back gives 1101 = 13.
:::
:::

::: example
## Add the BCD digits 9 and 7.

::: solution
1. **Add in binary.**
   $$\begin{aligned} 1001 + 0111 &= 1\,0000 \\ &= 16 \end{aligned}$$
   which is not a valid BCD digit and not the right display.
2. **Correct the sum.** Because the sum exceeds 9, add 6:
   $$1\,0000 + 0110 = 1\,0110$$
   a carry of 1 into the tens digit and 0110 = 6 in the units: 16.
3. **Why 6.** The correction skips the six codes, 1010 to 1111, that BCD never uses.

**Answer:** 1 0110 in BCD: a 1 in the tens digit and 6 in the units, 16.
:::
:::

::: example
## Encode the data 1011 in Hamming(7,4), flip bit 6, and find the error.

::: solution
1. **Compute the parity bits.** With data bits $d_1d_2d_3d_4$ = 1011 at positions 3, 5, 6 and 7:
   $$\begin{aligned} p_1 &= d_1 \oplus d_2 \oplus d_4 \\ &= 0 \\ p_2 &= d_1 \oplus d_3 \oplus d_4 \\ &= 1 \\ p_4 &= d_2 \oplus d_3 \oplus d_4 \\ &= 0 \end{aligned}$$
2. **Assemble the codeword.** The codeword, positions 1 to 7, is 0110011.
3. **Flip position 6.** The word becomes 0110001.
4. **Recheck the parity.** The parity over positions 1, 3, 5, 7 passes (0), the one over 2, 3, 6, 7 fails (1), and the one over 4, 5, 6, 7 fails (1).
5. **Read the syndrome.** The syndrome is 110 in binary, 6: flip position 6 back and the data is recovered.

**Answer:** the codeword is 0110011; with bit 6 flipped, the syndrome is 110 = 6, which points to the flipped bit.
:::
:::

::: check
given: n = 2..15 int
answer: 8*floor(n/8) + 4*(floor(n/4) + floor(n/8) - 2*floor((floor(n/4) + floor(n/8))/2)) + 2*(floor(n/2) + floor(n/4) - 2*floor((floor(n/2) + floor(n/4))/2)) + (n + floor(n/2) - 2*floor((n + floor(n/2))/2))
base: 2
width: 4

## Convert the binary number {n:bin4} to Gray code.

::: right
Right: {answer}, the number XORed with itself shifted right one place.
:::

::: misses
- [n] That's the binary value unchanged; XOR each bit with the one to its left.
- [any] Not yet. $G = B \oplus (B \gg 1)$.
:::
:::

::: check
kind: boolean
vars: B3, B2, B1, B0
answer: B3 ^ B2 ^ B1 ^ B0
ops: xor

## Write the even-parity bit for the data $B_3B_2B_1B_0$.

::: right
Right: the XOR of all four, which makes the total count of 1s even.
:::

::: misses
- [any] Not yet. The parity bit is 1 when the data has an odd number of 1s.
:::
:::

::: check
kind: parts
given: k = 4 | 11 | 26 | 57

## A Hamming code protects k = {k} data bits.

::: part
answer: ceil(log(k + 1 + ceil(log(k + 1)/log(2)))/log(2))
tolerance: 0

### How many parity bits does it need?

::: misses
- [any] The smallest r with $2^r \ge k + r + 1$.
:::
:::

::: part
answer: k/(k + ceil(log(k + 1 + ceil(log(k + 1)/log(2)))/log(2)))
tolerance: 0.5%

### What's its code rate, data bits over total bits?

::: misses
- [any] $\frac{k}{k + r}$.
:::
:::
:::

::: check
kind: parts
given: d = 2 | 3 | 4 | 7

## A code has minimum distance d = {d}.

::: part
answer: d - 1
tolerance: 0

### How many errors can it detect?

::: misses
- [any] $d - 1$.
:::
:::

::: part
answer: floor((d - 1)/2)
tolerance: 0

### How many can it correct?

::: misses
- [d - 1] Correcting needs the received word to be closer to the right codeword than any other.
- [any] $\left\lfloor\frac{d - 1}{2}\right\rfloor$.
:::
:::
:::

::: check
kind: parts
given: a = 5 | 7 | 8; b = 6 | 7 | 9

## The BCD digits {a} and {b} are added.

::: part
answer: a + b + 6*step(a + b - 10)
tolerance: 0

### What's the 5-bit binary result after the correction, as a number?

::: misses
- [a + b] When the sum exceeds 9, add 6.
- [any] Add 6 if the binary sum is 10 or more.
:::
:::

::: part
answer: a + b - 10*step(a + b - 10)
tolerance: 0

### What's the units digit?

::: misses
- [any] The low four bits after correcting.
:::
:::
:::

::: check
kind: python

## Write `hamming74_encode(d)` taking a list of 4 data bits and returning the 7-bit codeword (positions 1 to 7, parity at 1, 2, 4), and `hamming74_correct(c)` returning `(data, position)`: the corrected data bits and the position of the error it fixed (0 if none).

```python starter
def hamming74_encode(d):
    return [0, 0] + d[:1] + [0] + d[1:]

def hamming74_correct(c):
    return [c[2], c[4], c[5], c[6]], 0

print(hamming74_encode([1, 0, 1, 1]))
```

```python solution
def hamming74_encode(d):
    d1, d2, d3, d4 = d
    p1 = d1 ^ d2 ^ d4
    p2 = d1 ^ d3 ^ d4
    p4 = d2 ^ d3 ^ d4
    return [p1, p2, d1, p4, d2, d3, d4]

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

print(hamming74_encode([1, 0, 1, 1]))
```

```python tests
assert hamming74_encode([1, 0, 1, 1]) == [0, 1, 1, 0, 0, 1, 1], "1011 encodes to 0110011."
for n in range(16):
    d = [(n >> 3) & 1, (n >> 2) & 1, (n >> 1) & 1, n & 1]
    c = hamming74_encode(d)
    assert hamming74_correct(c) == (d, 0), "A clean codeword needs no correction."
    for p in range(7):
        r = list(c); r[p] ^= 1
        assert hamming74_correct(r) == (d, p + 1), f"A flip at position {p + 1} must be found and fixed."
```

::: right
Right. The syndrome is the binary number of the bad position, so correcting it is one lookup.
:::
:::

::: explain
## Why does a Hamming code's syndrome point directly at the bit in error?

::: model
Each parity bit checks the positions whose binary number has a particular bit set: the first checks positions with bit 0 set, the second those with bit 1 set, and so on. A single error at position p upsets exactly the checks corresponding to the 1 bits in p's binary number, and no others. Reading the failed checks as a binary number therefore spells out p itself. That's why the parity bits sit at positions 1, 2, 4 and so on: each is the only position checked by its own parity, so it never disturbs the others.
:::
:::

::: practice

::: check
given: k = 8 | 16 | 32 | 64
answer: ceil(log(k + 1 + ceil(log(k + 1)/log(2)))/log(2))
tolerance: 0

## How many Hamming parity bits protect {k} data bits?

::: misses
- [any] The smallest r with $2^r \ge k + r + 1$.
:::
:::

::: check
given: a = 2 | 6 | 9; b = 3 | 5 | 8
answer: a + b + 6*step(a + b - 10)
tolerance: 0

## BCD {a} + {b}: corrected 5-bit result as a number?

::: misses
- [any] Add 6 when the binary sum is 10 or more.
:::
:::
:::
