TExcelTAD
Home › Linear Algebra & Matrix Theory › Application: Error Correcting Codes

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

GF(2)={0,1}\mathrm{GF}(2) = \{0, 1\} is the field with 1+1=01 + 1 = 0 (Fields). Addition is XOR and multiplication is AND. Bit strings of length nn, with bitwise XOR as addition, form the vector space GF(2)n\mathrm{GF}(2)^n of dimension nn, with 2n2^n 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 nn and dimension kk is a kk-dimensional subspace CC of GF(2)n\mathrm{GF}(2)^n. Its 2k2^k vectors are the codewords. Each one carries kk bits of data in nn bits.

Hamming distance

The Hamming distance d(u,v)d(\mathbf{u}, \mathbf{v}) is the number of positions where u\mathbf{u} and v\mathbf{v} differ, which is the weight (number of 1s) of u+v\mathbf{u} + \mathbf{v}. The minimum distance dd 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 u+v\mathbf{u} + \mathbf{v} is again a codeword.

Minimum distance dd The code can
2 detect 1 error (a single parity bit)
3 correct 1 error, or detect 2
2t+12t + 1 correct tt errors

Why 3 is enough to correct one error: around each codeword, the strings at distance ≤1\le 1 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 p1,p2,p3p_1, p_2, p_3; positions 3, 5, 6, 7 hold the data bits d1,d2,d3,d4d_1, d_2, d_3, d_4. The parity-check matrix HH has the binary numbers 1 to 7 as its columns:

text
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 4

The code is the null space of HH: c\mathbf{c} is a codeword exactly when Hc=0(mod2)H\mathbf{c} = \mathbf{0} \pmod 2. Each row of HH is one parity rule; for example, row 1 says that positions 1, 3, 5, 7 contain an even number of 1s, so p1=d1+d2+d4p_1 = d_1 + d_2 + d_4. HH has rank 3, so by rank–nullity the null space has dimension 7−3=47 - 3 = 4: 24=162^4 = 16 codewords, one for each 4-bit message.

The generator matrix GG (4×74 \times 7) has a basis of the code as its rows, the codewords for the messages 1000, 0100, 0010, 0001. Encoding a message m\mathbf{m} (a row vector) is c=mG\mathbf{c} = \mathbf{m}G. Since every row of GG is in the null space, GHT=0GH^T = 0.

python · try it yourself
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 c\mathbf{c} is sent and r=c+e\mathbf{r} = \mathbf{c} + \mathbf{e} arrives, where e\mathbf{e} is the error pattern. The receiver computes the syndrome

s=Hr=Hc+He=0+He=He\mathbf{s} = H\mathbf{r} = H\mathbf{c} + H\mathbf{e} = \mathbf{0} + H\mathbf{e} = H\mathbf{e}

The syndrome depends only on the error, not on the message. If e\mathbf{e} has a single 1 in position jj, then HeH\mathbf{e} is column jj of HH, which is the binary number jj. So the syndrome, read as a binary number, is the position of the flipped bit (and s=0\mathbf{s} = \mathbf{0} means no error was detected). Flip it back and read the data from positions 3, 5, 6, 7.

python · try it yourself
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 16⋅(1+7)=128=2716 \cdot (1 + 7) = 128 = 2^7 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 GF(28)\mathrm{GF}(2^8), 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 p1=d1+d2+d4p_1 = d_1 + d_2 + d_4, p2=d1+d3+d4p_2 = d_1 + d_3 + d_4, p3=d2+d3+d4(mod2)p_3 = d_2 + d_3 + d_4 \pmod 2 and the layout p1 p2 d1 p3 d2 d3 d4p_1\ p_2\ d_1\ p_3\ d_2\ d_3\ d_4.

Answer
Solution
d1 d2 d3 d4=0 1 1 0p1=0+1+0=1p2=0+1+0=1p3=1+1+0=0(1+1=0 in GF(2))codeword=p1 p2 d1 p3 d2 d3 d4=1 1 0 0 1 1 0\begin{aligned} d_1\ d_2\ d_3\ d_4 &= 0\ 1\ 1\ 0 \\ p_1 &= 0 + 1 + 0 = 1 \\ p_2 &= 0 + 1 + 0 = 1 \\ p_3 &= 1 + 1 + 0 = 0 && (1 + 1 = 0 \text{ in } \mathrm{GF}(2)) \\ \text{codeword} &= p_1\ p_2\ d_1\ p_3\ d_2\ d_3\ d_4 = 1\ 1\ 0\ 0\ 1\ 1\ 0 \end{aligned}

Equivalently, the sum of rows 2 and 3 of GG: 1001100+0101010=11001101001100 + 0101010 = 1100110.

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
row 1 (positions 1, 3, 5, 7):1+1+1+0=1row 2 (positions 2, 3, 6, 7):1+1+1+0=1row 3 (positions 4, 5, 6, 7):0+1+1+0=0syndrome=1⋅1+1⋅2+0⋅4=3→flip bit 3: 1100110data=positions 3, 5, 6, 7=0 1 1 0\begin{aligned} &\text{row 1 (positions 1, 3, 5, 7):} && 1 + 1 + 1 + 0 = 1 \\ &\text{row 2 (positions 2, 3, 6, 7):} && 1 + 1 + 1 + 0 = 1 \\ &\text{row 3 (positions 4, 5, 6, 7):} && 0 + 1 + 1 + 0 = 0 \\ &\text{syndrome} = 1 \cdot 1 + 1 \cdot 2 + 0 \cdot 4 = 3 \quad \to \quad \text{flip bit 3: } 1100110 \\ &\text{data} = \text{positions 3, 5, 6, 7} = 0\ 1\ 1\ 0 \end{aligned}

Exercise 3: Counting

How many vectors does GF(2)7\mathrm{GF}(2)^7 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

27=1282^7 = 128. The code has dimension 4, so 24=162^4 = 16 codewords. Each codeword has 7 neighbours at distance 1, so 16⋅8=12816 \cdot 8 = 128 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 ii and jj give syndrome iXORji \mathbin{\text{XOR}} j, 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".

python · try it yourself
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 1+11 + 1?

  1. 2
  2. 0
  3. 1
  4. undefined

A received Hamming(7,4) word has syndrome (1,0,1)(1, 0, 1), read as bits for 1, 2, 4. Which bit was flipped?

  1. Bit 3
  2. Bit 5
  3. Bit 6
  4. Bit 2

Why is the minimum distance of a linear code equal to its smallest nonzero codeword weight?

  1. Because all codewords have the same weight
  2. Because d(u,v)d(\mathbf{u}, \mathbf{v}) is the weight of u+v\mathbf{u} + \mathbf{v}, which is itself a codeword
  3. Because the code is perfect
  4. Because HH has rank 3