TExcelTAD
Home › Information Theory › The (7,4) Hamming Code

The (7,4) Hamming Code

Richard Hamming, frustrated by weekend computer jobs that crashed on single-bit errors, invented in 1950 a code that corrects any single error in a block of 7 bits while carrying 4 data bits. Its rate 47\frac{4}{7} is far better than the 13\frac{1}{3} of a triple repetition code with the same error-correcting power for single errors.

Encoding with parity bits

Four source bits s1s2s3s4s_1s_2s_3s_4 are followed by three parity bits, each the XOR (sum modulo 2) of three source bits:

t5=s1⊕s2⊕s3,t6=s2⊕s3⊕s4,t7=s1⊕s3⊕s4t_5 = s_1 \oplus s_2 \oplus s_3, \qquad t_6 = s_2 \oplus s_3 \oplus s_4, \qquad t_7 = s_1 \oplus s_3 \oplus s_4

Picture three overlapping circles, each containing four bits whose sum must be even. In matrix form the codeword is t=sG mod 2\mathbf{t} = \mathbf{s}G \bmod 2 with the 4×74 \times 7 generator matrix G=[I4∣P]G = [I_4 \mid P]:

python · try it yourself
import numpy as np

P = np.array([[1, 0, 1],
              [1, 1, 0],
              [1, 1, 1],
              [0, 1, 1]])
G = np.hstack([np.eye(4, dtype=int), P])
print("G =\n", G)
codewords = np.array([np.array(s) @ G % 2 for s in np.ndindex(2, 2, 2, 2)])
for s, t in zip(np.ndindex(2, 2, 2, 2), codewords[:6]):
    print("".join(map(str, s)), "->", "".join(map(str, t)))
print("... 16 codewords in total")
G =
 [[1 0 0 0 1 0 1]
 [0 1 0 0 1 1 0]
 [0 0 1 0 1 1 1]
 [0 0 0 1 0 1 1]]
0000 -> 0000000
0001 -> 0001011
0010 -> 0010111
0011 -> 0011100
0100 -> 0100110
0101 -> 0101101
... 16 codewords in total

Minimum distance 3

Any two distinct codewords differ in at least 3 positions. For a linear code this equals the smallest weight of a non-zero codeword (Linear Block Codes):

python · try it yourself
import numpy as np

P = np.array([[1, 0, 1], [1, 1, 0], [1, 1, 1], [0, 1, 1]])
G = np.hstack([np.eye(4, dtype=int), P])
codewords = np.array([np.array(s) @ G % 2 for s in np.ndindex(2, 2, 2, 2)])
weights = codewords.sum(axis=1)
print("weight distribution:", {int(w): int(np.sum(weights == w)) for w in np.unique(weights)})
D = (codewords[:, None, :] != codewords[None, :, :]).sum(axis=2)
print("minimum distance between distinct codewords:", int(D[D > 0].min()))
weight distribution: {0: 1, 3: 7, 4: 7, 7: 1}
minimum distance between distinct codewords: 3

With distance 3, the spheres of radius 1 around the 16 codewords do not overlap. Each sphere holds 1+7=81 + 7 = 8 words and 16×8=128=2716 \times 8 = 128 = 2^7: they fill the whole space exactly. Hamming codes are perfect codes.

Decoding with the syndrome

The decoder recomputes the three parity checks on the received word r\mathbf{r}. The pattern of failed checks, the syndrome z=Hr mod 2\mathbf{z} = H\mathbf{r} \bmod 2, is different for each of the 7 single-bit errors, so it points to the bit to flip (Parity-Check Matrices and Syndromes).

python · try it yourself
import numpy as np

P = np.array([[1, 0, 1], [1, 1, 0], [1, 1, 1], [0, 1, 1]])
G = np.hstack([np.eye(4, dtype=int), P])
H = np.hstack([P.T, np.eye(3, dtype=int)])
syndrome_to_bit = {tuple(H[:, j]): j for j in range(7)}

def decode(r):
    z = tuple(H @ r % 2)
    r = r.copy()
    if any(z):
        r[syndrome_to_bit[z]] ^= 1
    return r[:4]

s = np.array([1, 0, 1, 1])
t = s @ G % 2
for pos in range(7):
    r = t.copy(); r[pos] ^= 1
    print(f"error at bit {pos}: syndrome {H @ r % 2}, decoded {decode(r)}, correct: {np.array_equal(decode(r), s)}")
error at bit 0: syndrome [1 0 1], decoded [1 0 1 1], correct: True
error at bit 1: syndrome [1 1 0], decoded [1 0 1 1], correct: True
error at bit 2: syndrome [1 1 1], decoded [1 0 1 1], correct: True
error at bit 3: syndrome [0 1 1], decoded [1 0 1 1], correct: True
error at bit 4: syndrome [1 0 0], decoded [1 0 1 1], correct: True
error at bit 5: syndrome [0 1 0], decoded [1 0 1 1], correct: True
error at bit 6: syndrome [0 0 1], decoded [1 0 1 1], correct: True

Performance on a BSC

The decoder fails when two or more of the 7 bits flip. Block error probability is 1−(1−f)7−7f(1−f)6≈21f21 - (1 - f)^7 - 7f(1 - f)^6 \approx 21f^2:

python · try it yourself
import numpy as np

P = np.array([[1, 0, 1], [1, 1, 0], [1, 1, 1], [0, 1, 1]])
G = np.hstack([np.eye(4, dtype=int), P]); H = np.hstack([P.T, np.eye(3, dtype=int)])
lookup = np.zeros(8, dtype=int) - 1
for j in range(7):
    lookup[H[:, j] @ [4, 2, 1]] = j

rng = np.random.default_rng(0)
f, blocks = 0.1, 100_000
S = rng.integers(0, 2, (blocks, 4))
R = (S @ G % 2) ^ (rng.random((blocks, 7)) < f)
z = (R @ H.T % 2) @ [4, 2, 1]
flip = lookup[z]
rows = np.nonzero(flip >= 0)[0]
R[rows, flip[rows]] ^= 1
block_err = np.mean(np.any(R[:, :4] != S, axis=1))
bit_err = np.mean(R[:, :4] != S)
print(f"block error {block_err:.4f} (exact {1 - 0.9**7 - 7 * 0.1 * 0.9**6:.4f}), bit error {bit_err:.4f}, rate 4/7")
block error 0.1506 (exact 0.1497), bit error 0.0675, rate 4/7

Compared with R3R_3 (bit error 0.028 at rate 13\frac{1}{3}), the Hamming code has a higher bit error rate here, around 0.07, but a much higher rate. At smaller ff its 21f221f^2 block error becomes tiny.

In software

  • SECDED memory (ECC RAM) uses an extended Hamming code: 64 data bits plus 8 check bits correct any single error and detect any double error in each word.
  • Hamming codes exist for every length 2m−12^m - 1 with mm parity bits: (7,4), (15,11), (31,26), ... The rate approaches 1 but each still corrects only one error per block.

Exercises

Exercise 1: Encode by hand

Encode s=0110\mathbf{s} = 0110.

Answer

0110001.

Solution

t5=0⊕1⊕1=0t_5 = 0 \oplus 1 \oplus 1 = 0, t6=1⊕1⊕0=0t_6 = 1 \oplus 1 \oplus 0 = 0, t7=0⊕1⊕0=1t_7 = 0 \oplus 1 \oplus 0 = 1.

Exercise 2: Two errors

What happens when two bits of a Hamming codeword are flipped?

Answer

The decoder flips a third bit and outputs a wrong codeword.

Solution

The syndrome of two errors is the XOR of two columns of HH, which equals some third column, so the decoder "corrects" a bit that was right. The result is at distance 3 from the sent codeword.

Exercise 3: Decode a word (code)

Decode the received word 1100110 with the lesson's HH.

Answer

The syndrome is 101, pointing to bit 0; the decoded data are 0100.

Solution
python · try it yourself
import numpy as np

P = np.array([[1, 0, 1], [1, 1, 0], [1, 1, 1], [0, 1, 1]])
H = np.hstack([P.T, np.eye(3, dtype=int)])
r = np.array([1, 1, 0, 0, 1, 1, 0])
z = H @ r % 2
j = next(j for j in range(7) if np.array_equal(H[:, j], z))
r[j] ^= 1
print("syndrome:", z, " flipped bit:", j, " data:", r[:4])
syndrome: [1 0 1]  flipped bit: 0  data: [0 1 0 0]

Test yourself

How many errors per block can the (7,4) Hamming code correct?

  1. 1
  2. 2
  3. 3
  4. 4

Why is the Hamming code called perfect?

  1. The radius-1 spheres around codewords fill the whole space exactly
  2. It corrects all errors
  3. It reaches capacity
  4. Its rate is 1

The syndrome of a single error at position j is…

  1. column j of the parity-check matrix
  2. row j of the generator
  3. zero
  4. the codeword itself