Computing Library › Worked Examples
Worked Examples

Hamming(7,4) Encode and Decode

Encode four data bits into a seven-bit codeword, inject a single-bit error, and locate it from the syndrome.

Problem

The Hamming(7,4) code adds three parity bits to four data bits so that any single-bit error can be detected and corrected. Each parity bit checks a specific subset of positions; a single error flips a unique pattern of parity checks, the syndrome, that points directly at the corrupted bit.

Encoding

Kronos motion — data assimilation

Positions 1,2,4 are parity bits; 3,5,6,7 carry data. Parity bit p_i covers all positions whose index has bit i set. The syndrome, read as a binary number, equals the position of the error, which is the elegance of the numbering.

python
import numpy as np
G=np.array([[1,1,0,1],[1,0,1,1],[1,0,0,0],[0,1,1,1],[0,1,0,0],[0,0,1,0],[0,0,0,1]])%2
d=np.array([1,0,1,1])
c=(G@d)%2                     # 7-bit codeword
c[4]^=1                       # inject error at position 5 (index 4)
H=np.array([[0,0,0,1,1,1,1],[0,1,1,0,0,1,1],[1,0,1,0,1,0,1]])
syn=(H@c)%2
pos=syn[0]*4+syn[1]*2+syn[2]  # wait: read syndrome as binary position
print('syndrome',syn,'error at position',int(''.join(map(str,syn)),2))

Result

The parity-check matrix H multiplies the received word to give a 3-bit syndrome. A zero syndrome means no detected error; otherwise the syndrome read as a binary number is exactly the position of the flipped bit, here position 5. Flipping that bit back recovers the original codeword. Hamming(7,4) corrects any single error and detects (but cannot correct) any double error.