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 is far better than the of a triple repetition code with the same error-correcting power for single errors.
Encoding with parity bits
Four source bits are followed by three parity bits, each the XOR (sum modulo 2) of three source bits:
Picture three overlapping circles, each containing four bits whose sum must be even. In matrix form the codeword is with the generator matrix :
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):
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 words and : 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 . The pattern of failed checks, the syndrome , is different for each of the 7 single-bit errors, so it points to the bit to flip (Parity-Check Matrices and Syndromes).
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 :
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 (bit error 0.028 at rate ), the Hamming code has a higher bit error rate here, around 0.07, but a much higher rate. At smaller its 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 with 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 .
Answer
0110001.
Solution
, , .
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 , 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 .
Answer
The syndrome is 101, pointing to bit 0; the decoded data are 0100.
Solution
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
- 2
- 3
- 4
Why is the Hamming code called perfect?
- The radius-1 spheres around codewords fill the whole space exactly
- It corrects all errors
- It reaches capacity
- Its rate is 1
The syndrome of a single error at position j is…
- column j of the parity-check matrix
- row j of the generator
- zero
- the codeword itself