Application: Error Correcting Codes
Memory chips, QR codes, deep-space probes and network links all have to survive flipped bits. An error-correcting code adds a few redundant bits so that the receiver can find and repair errors. The cleanest such codes are subspaces of the vector space of bit strings over GF(2), and the encoder and decoder are just matrix products. We build the classic Hamming(7,4) code, which fixes any single flipped bit in a 7-bit block.
Bit strings form a vector space
is the field with (Fields). Addition is XOR and multiplication is AND. Bit strings of length , with bitwise XOR as addition, form the vector space of dimension , with vectors. All of linear algebra works here (span, null space, rank, row reduction), only with arithmetic modulo 2, as in Matrix Arithmetic Modulo p.
A linear code of length and dimension is a -dimensional subspace of . Its vectors are the codewords. Each one carries bits of data in bits.
Hamming distance
The Hamming distance is the number of positions where and differ, which is the weight (number of 1s) of . The minimum distance of a code is the smallest distance between two different codewords. For a linear code it is simply the smallest weight of a nonzero codeword, because is again a codeword.
| Minimum distance | The code can |
|---|---|
| 2 | detect 1 error (a single parity bit) |
| 3 | correct 1 error, or detect 2 |
| correct errors |
Why 3 is enough to correct one error: around each codeword, the strings at distance form a "ball", and these balls cannot overlap when codewords are 3 apart. A received string with one flipped bit lies in exactly one ball, and the decoder picks its centre.
The Hamming(7,4) code
Number the positions 1 to 7. Positions 1, 2 and 4 (the powers of two) hold parity bits ; positions 3, 5, 6, 7 hold the data bits . The parity-check matrix has the binary numbers 1 to 7 as its columns:
position: 1 2 3 4 5 6 7
H = [[1, 0, 1, 0, 1, 0, 1], bit 1 of the position number
[0, 1, 1, 0, 0, 1, 1], bit 2
[0, 0, 0, 1, 1, 1, 1]] bit 4The code is the null space of : is a codeword exactly when . Each row of is one parity rule; for example, row 1 says that positions 1, 3, 5, 7 contain an even number of 1s, so . has rank 3, so by rank–nullity the null space has dimension : codewords, one for each 4-bit message.
The generator matrix () has a basis of the code as its rows, the codewords for the messages 1000, 0100, 0010, 0001. Encoding a message (a row vector) is . Since every row of is in the null space, .
import numpy as np
from itertools import product
H = np.array([[(j >> b) & 1 for j in range(1, 8)] for b in range(3)])
G = np.array([[1, 1, 1, 0, 0, 0, 0], # rows: codewords of 1000, 0100, 0010, 0001
[1, 0, 0, 1, 1, 0, 0],
[0, 1, 0, 1, 0, 1, 0],
[1, 1, 0, 1, 0, 0, 1]])
print("H =\n", H)
print("G H^T mod 2 =", ((G @ H.T) % 2).tolist())
codewords = [tuple(int(b) for b in (np.array(m) @ G) % 2) for m in product([0, 1], repeat=4)]
weights = sorted(sum(c) for c in codewords if any(c))
print("number of codewords:", len(set(codewords)))
print("minimum distance:", weights[0], " weights:", weights)H =
[[1 0 1 0 1 0 1]
[0 1 1 0 0 1 1]
[0 0 0 1 1 1 1]]
G H^T mod 2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
number of codewords: 16
minimum distance: 3 weights: [3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 7]
Decoding with the syndrome
Suppose the codeword is sent and arrives, where is the error pattern. The receiver computes the syndrome
The syndrome depends only on the error, not on the message. If has a single 1 in position , then is column of , which is the binary number . So the syndrome, read as a binary number, is the position of the flipped bit (and means no error was detected). Flip it back and read the data from positions 3, 5, 6, 7.
import numpy as np
H = np.array([[(j >> b) & 1 for j in range(1, 8)] for b in range(3)])
G = np.array([[1, 1, 1, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0, 0],
[0, 1, 0, 1, 0, 1, 0], [1, 1, 0, 1, 0, 0, 1]])
def encode(data):
return (np.array(data) @ G) % 2
def decode(r):
r = r.copy()
s = (H @ r) % 2
pos = int(s[0] + 2 * s[1] + 4 * s[2]) # syndrome as a binary number
if pos:
r[pos - 1] ^= 1 # flip the bad bit back
return r[[2, 4, 5, 6]], pos # data sits in positions 3, 5, 6, 7
data = [1, 0, 1, 1]
c = encode(data)
print("data", data, "-> codeword", "".join(map(str, c)))
for flip in [None, 0, 4, 6]:
r = c.copy()
if flip is not None:
r[flip] ^= 1
out, pos = decode(r)
print("received", "".join(map(str, r)), " syndrome ->", pos, " decoded", out.tolist())data [1, 0, 1, 1] -> codeword 0110011
received 0110011 syndrome -> 0 decoded [1, 0, 1, 1]
received 1110011 syndrome -> 1 decoded [1, 0, 1, 1]
received 0110111 syndrome -> 5 decoded [1, 0, 1, 1]
received 0110010 syndrome -> 7 decoded [1, 0, 1, 1]
Every single-bit error is repaired. Hamming(7,4) is a perfect code: the 16 balls of radius 1 contain strings, so they fill the whole space with no gaps. The price is that two errors are always "corrected" to the wrong codeword (see Exercise 4).
In software
- ECC memory: server RAM uses an extended Hamming code (SECDED, single error correction and double error detection) on every 64-bit word, with 8 check bits.
- Storage and networks: RAID 6, QR codes, CDs and DVDs, SSDs, Wi-Fi and 5G use stronger linear codes (Reed–Solomon over , BCH, LDPC, polar codes). The encoder is a matrix product; decoding starts with a syndrome.
- Post-quantum cryptography: the McEliece cryptosystem hides a structured linear code behind a random-looking generator matrix; decoding a random linear code is believed hard even for quantum computers (Cryptography Basics).
- Checksums: a parity bit and CRCs are linear maps over GF(2) as well, but they detect errors rather than correct them.
Exercises
Exercise 1: Encode by hand
Encode the data bits 0110 with the parity rules , , and the layout .
Answer
Solution
Equivalently, the sum of rows 2 and 3 of : .
Exercise 2: Find the error
The word 1110110 arrives. Compute the syndrome, correct the error and read off the data.
Answer
Syndrome 3 (binary 011): bit 3 was flipped; the codeword is 1100110 and the data is 0110.
Solution
Exercise 3: Counting
How many vectors does have? How many are codewords, and how many are within distance 1 of some codeword?
Answer
128 vectors, 16 codewords, and all 128 are within distance 1 of exactly one codeword.
Solution
. The code has dimension 4, so codewords. Each codeword has 7 neighbours at distance 1, so strings are within distance 1 of a codeword. The balls cannot overlap (minimum distance 3), so they cover the space exactly once.
Exercise 4: Two errors
Flip every pair of bits in a codeword and decode. How many of the 21 double errors are decoded correctly? Then add an 8th bit holding the overall parity (extended Hamming code) and show that every double error is now detected.
Answer
0 of 21 are decoded correctly by Hamming(7,4); with the overall parity bit, all 21 are flagged as "double error".
Solution
Two flips at positions and give syndrome , which is nonzero and points at a third position, so the decoder adds a third error. With an overall parity bit, one error makes the overall parity odd, while two errors keep it even but give a nonzero syndrome: that combination means "two errors, cannot correct".
import numpy as np
from itertools import combinations
H = np.array([[(j >> b) & 1 for j in range(1, 8)] for b in range(3)])
c = np.array([1, 1, 0, 0, 1, 1, 0]) # codeword of 0110
c8 = np.append(c, c.sum() % 2) # extended code: add overall parity
wrong, detected = 0, 0
for i, j in combinations(range(7), 2):
r = c8.copy(); r[i] ^= 1; r[j] ^= 1
s = (H @ r[:7]) % 2
pos = int(s[0] + 2 * s[1] + 4 * s[2])
fixed = r[:7].copy(); fixed[pos - 1] ^= 1
wrong += not np.array_equal(fixed, c) # plain Hamming(7,4) decoding
detected += pos != 0 and r.sum() % 2 == 0 # SECDED rule: syndrome != 0, parity even
print("double errors:", len(list(combinations(range(7), 2))))
print("miscorrected by Hamming(7,4):", wrong)
print("detected by the extended code:", detected)double errors: 21
miscorrected by Hamming(7,4): 21
detected by the extended code: 21
Test yourself
In GF(2), what is ?
- 2
- 0
- 1
- undefined
A received Hamming(7,4) word has syndrome , read as bits for 1, 2, 4. Which bit was flipped?
- Bit 3
- Bit 5
- Bit 6
- Bit 2
Why is the minimum distance of a linear code equal to its smallest nonzero codeword weight?
- Because all codewords have the same weight
- Because is the weight of , which is itself a codeword
- Because the code is perfect
- Because has rank 3