Hamming (7,4) code
Add 3 parity bits to 4 data bits so that if one bit is flipped on the way, the syndrome tells exactly where, and it can be fixed.
In the Hamming (7,4) code, positions 1, 2 and 4 (the powers of 2) are parity bits and the rest are data:
Read the full explanation ↓- Time:
O(1) - Space:
O(1) - Grimaldi, chapter 16
The data 1011; the code word is 0110011. Bit 5 is flipped on the way, and the syndrome points exactly at 5.
def hamming(data, error):# Positions 1 … 7 hold p1 p2 d1 p3 d2 d3 d4; c[k - 1] is the bit at position k.d = [int(b) for b in data]c = [0, 0, d[0], 0, d[1], d[2], d[3]]table = [["p1", "p2", "d1", "p3", "d2", "d3", "d4"], c]c[0] = c[2] ^ c[4] ^ c[6]c[1] = c[2] ^ c[5] ^ c[6]c[3] = c[4] ^ c[5] ^ c[6]sent = "".join(str(b) for b in c)if error:c[error - 1] = c[error - 1] ^ 1# Each check covers the positions whose number has that bit set; together they spell the bad position.s1 = c[0] ^ c[2] ^ c[4] ^ c[6]s2 = c[1] ^ c[2] ^ c[5] ^ c[6]s4 = c[3] ^ c[4] ^ c[5] ^ c[6]syndrome = s1 + 2 * s2 + 4 * s4if syndrome:c[syndrome - 1] = c[syndrome - 1] ^ 1decoded = f"{c[2]}{c[4]}{c[5]}{c[6]}"return decoded
Start
The table is still empty.
Local variables
Orange = changed in this step
Call stack
- hamming()line 1
Explanation
The idea
In the Hamming (7,4) code, positions 1, 2 and 4 (the powers of 2) are parity bits and the rest are data:
p1checks the positions whose number has bit 1 set: 1, 3, 5, 7;p2checks positions 2, 3, 6, 7;p4checks positions 4, 5, 6, 7.
Detecting and correcting
The receiver recomputes all three checks. If the bit at position k was flipped, exactly the checks covering k fail,
that is, the bits of the number k. So the binary number formed by the failed checks (the syndrome) is k,
and that bit is flipped back. A zero syndrome means no error.
The code corrects any single-bit error but not two.
What to watch in the trace
- The table gives each position's name and bit; watch which bit gets flipped and fixed again.