Skip to content

Foundations · Chapter F.7

Parity, Hamming codes and error correction

How computers notice and repair flipped bits: parity, Hamming distance, the check-bit bound, a Hamming(7,4) code encoded, corrupted and corrected live, SECDED in ECC memory, CRC-32 computed by hand and checked against zlib, and where these codes are used today.

Bits don't always stay put. A neutron from a cosmic ray or an alpha particle from the chip's own packaging can flip a bit in memory; electrical noise corrupts bits on a wire; flash cells wear out and leak. The fix is always the same idea: store or send a few redundant bits, computed from the data, so that damage becomes visible. With a little redundancy you can detect errors; with more, you can correct them.

Parity

The simplest scheme adds a single parity bit to a group of data bits, chosen so that the total number of 1 bits is even (even parity) or odd (odd parity). The letter C is 100 0011 in ASCII: three 1 bits, so with even parity its parity bit is 1, making 1100 0011. If any single bit flips in transit, the count of 1s becomes odd and the receiver knows something is wrong.

Parity catches any odd number of flipped bits and misses any even number: two flips cancel out. It also can't say which bit flipped, so it can only detect, not correct. x86 still computes a parity bit on every arithmetic result, in the PF flag, which is set when the low byte of the result has an even number of 1 bits. In the simulator, test al, al with al = 0x41 (two 1 bits) sets PF to 1, and with 0x43 (three) sets it to 0. It's a feature inherited from Intel's 8-bit processors of the 1970s.

Hamming distance

To reason about what a code can do, Richard Hamming introduced, in 1950, a way to measure how different two bit strings are. The Hamming distance between two strings of the same length is the number of positions where they differ: XOR them and count the 1 bits. 1011001 and 1001011 differ in two positions, so their distance is 2.

A code is the set of valid codewords: data bits plus check bits, computed by a fixed rule. The distance of a code is the smallest distance between any two of its codewords. It determines everything:

  • To detect up to d flipped bits, the code needs distance at least d + 1: then d flips can't turn one valid codeword into another.
  • To correct up to d flipped bits, it needs distance at least 2d + 1: then a codeword with d flips is still closer to the original than to any other valid one.

A parity code has distance 2: every single flip produces an invalid word, so it detects one error and corrects none. To correct single errors, you need distance 3.

How many check bits?

Say each word has m data bits and r check bits, n = m + r in all. To correct any single error, every valid codeword needs n + 1 patterns set aside for itself: the codeword and the n words one flip away. There are 2ᵐ codewords and only 2ⁿ patterns, so (n + 1) × 2ᵐ ≤ 2ⁿ, which simplifies to m + r + 1 ≤ 2ʳ. The smallest r for common word sizes:

Data bitsCheck bitsTotalOverhead
43775 %
841250 %
1652131 %
3263819 %
6477111 %
12881366 %

The number of check bits grows only with the logarithm of the word size, so correcting errors in big words is cheap.

A Hamming code, step by step

Hamming also showed how to reach that bound. Number the bits of the codeword from 1. The positions that are powers of two (1, 2, 4, 8…) hold parity bits; all other positions hold data. Each parity bit covers the positions whose number, in binary, has that bit set:

Parity bitCovers positions
1 (binary 001)1, 3, 5, 7
2 (binary 010)2, 3, 6, 7
4 (binary 100)4, 5, 6, 7

With 7 positions, that's the Hamming(7,4) code: 4 data bits in positions 3, 5, 6 and 7, and 3 parity bits. Encode the data 1011:

position:  1  2  3  4  5  6  7
role:      p1 p2 d1 p4 d2 d3 d4
data:            1     0  1  1
p1 = d1 ⊕ d2 ⊕ d4 = 1 ⊕ 0 ⊕ 1 = 0
p2 = d1 ⊕ d3 ⊕ d4 = 1 ⊕ 1 ⊕ 1 = 1
p4 = d2 ⊕ d3 ⊕ d4 = 0 ⊕ 1 ⊕ 1 = 0
codeword:  0  1  1  0  0  1  1

(⊕ is XOR: the result is 1 when an odd number of inputs are 1, which is exactly a parity computation.) Now suppose bit 5 flips. The receiver recomputes each parity check over the bits it covers, including the parity bit itself. Each failing check contributes its own position number, and their sum, the syndrome, is the position of the bad bit:

  • check 1 (positions 1, 3, 5, 7) fails: +1
  • check 2 (positions 2, 3, 6, 7) passes
  • check 4 (positions 4, 5, 6, 7) fails: +4

The syndrome is 1 + 4 = 5: flip bit 5 back and the data is restored. That's the trick behind the positions: every position has a unique binary number, and the set of checks covering it spells out that number. A syndrome of 0 means no error. The program below runs the whole sequence:

Live · Hamming(7,4): encode, corrupt, correct

Try it: Press Step to run one instruction, Run to animate or Continue to finish; the L2–L7 buttons zoom in and out one level at a time.

C source · click a line number for a breakpoint
  1. /* bit i of the codeword (1..7) is stored in c[i]; c[0] is unused */
  2. int c[8];
  3. void encode(int data) { /* data = d1 d2 d3 d4, d1 first */
  4. c[3] = (data >> 3) & 1;
  5. c[5] = (data >> 2) & 1;
  6. c[6] = (data >> 1) & 1;
  7. c[7] = data & 1;
  8. c[1] = c[3] ^ c[5] ^ c[7]; /* checks positions with bit 1 set */
  9. c[2] = c[3] ^ c[6] ^ c[7]; /* ... with bit 2 set */
  10. c[4] = c[5] ^ c[6] ^ c[7]; /* ... with bit 4 set */
  11. }
  12. void show(char *label) {
  13. printf("%s", label);
  14. for (int i = 1; i <= 7; i++)
  15. printf("%d", c[i]);
  16. printf("\n");
  17. }
  18. int syndrome(void) {
  19. int s1 = c[1] ^ c[3] ^ c[5] ^ c[7];
  20. int s2 = c[2] ^ c[3] ^ c[6] ^ c[7];
  21. int s4 = c[4] ^ c[5] ^ c[6] ^ c[7];
  22. return s1 + 2 * s2 + 4 * s4; /* 0 = no error, else the bad position */
  23. }
  24. int main() {
  25. encode(0xB); /* data bits 1011 */
  26. show("sent: ");
  27. c[5] = c[5] ^ 1; /* a cosmic ray flips bit 5 */
  28. show("received: ");
  29. int s = syndrome();
  30. printf("syndrome: %d\n", s);
  31. if (s != 0)
  32. c[s] = c[s] ^ 1; /* flip it back */
  33. show("corrected: ");
  34. return s;
  35. }
step 0
Loading emulator…
Your program as you wrote it: the current line, its variables by name, and its output.

It prints the codeword 0110011, the corrupted 0110111, a syndrome of 5, and the corrected 0110011. Change the flipped position to anything from 1 to 7 and the syndrome follows. Checking all 16 codewords confirms that this code has distance 3.

Distance 3 also means two errors fool it. Flip bits 2 and 6 of 0110011 instead, and the syndrome comes out as 4: the decoder "corrects" bit 4, which was fine, and now three bits are wrong. The same method works at any size: 16 data bits need 5 check bits, and the principle doesn't change.

SECDED: what ECC memory does

The standard fix for the two-error problem is to add one more bit: an overall parity bit over the whole codeword. The code's distance becomes 4, enough to correct one error and detect two. This is SECDED (single error correction, double error detection):

  • syndrome 0, overall parity correct: no error;
  • syndrome ≠ 0, overall parity wrong: one error, at the syndrome's position, so correct it;
  • syndrome ≠ 0, overall parity correct: two errors: report them, don't touch the data.

Try both codes on the codeword 0110011 below. Click any bit to flip it and watch which checks fail: with one flip, the failing checks always add up to its position and the decoder repairs it. Flip a second bit and the plain Hamming decoder confidently "corrects" a third one. Then add the SECDED bit and flip two bits again: the overall parity now comes out correct, so the decoder reports the double error instead of making it worse.

Hamming(7,4): flip bits, watch the checks

Try it: Click any bit of the codeword to flip it, as a cosmic ray would. Flip one bit, then a second one, then switch on SECDED and try two again.

Data d1..d4→ sent 0110011
Received codeword (click a bit)
check 1 okcheck 2 okcheck 4 ok01121304051617
check 10 ⊕ 1 ⊕ 0 ⊕ 1 = 0okpositions 1, 3, 5, 7
check 21 ⊕ 1 ⊕ 1 ⊕ 1 = 0okpositions 2, 3, 6, 7
check 40 ⊕ 0 ⊕ 1 ⊕ 1 = 0okpositions 4, 5, 6, 7
syndrome0

Syndrome 0: no error found, the word is accepted as it is.

Nothing flipped yet.

bits flipped: 0 · received 0110011 · after decoding 0110011

ECC memory applies SECDED to each 64-bit word, with 8 check bits: the 7 from the table above, plus the overall parity bit. An ECC memory module is therefore 72 bits wide instead of 64, usually with one extra memory chip for every eight, so 12.5 % more memory, which the memory controller checks on every read. Single-bit errors are fixed silently and logged; double-bit errors are reported to the operating system, which typically stops the affected program or the whole machine rather than let corrupted data spread. Controllers also scrub memory in the background, reading and correcting every word periodically so that single errors don't accumulate into double ones. Servers use ECC memory almost universally; most consumer PCs and phones don't. DDR5 chips add their own on-die ECC internally, but it corrects errors inside the chip and doesn't replace ECC across the module.

Larger systems go further: IBM's Chipkill and similar schemes spread each word across chips so that the data survives the failure of a whole memory chip.

CRCs: catching bursts

Noise on a wire or a scratch on a disk tends to damage several neighboring bits at once, a burst error. For detecting those, the tool of choice is the cyclic redundancy check (CRC). The idea: treat the message as a huge binary polynomial, divide it by a fixed generator polynomial using XOR instead of subtraction, and send the remainder along with the data. The receiver repeats the division; if the remainder differs, the data was damaged.

CRC-32, the variant used by Ethernet, ZIP, gzip and PNG, has a 32-bit remainder. It's short to write in software, one bit at a time. The constant 0xEDB88320 is the generator polynomial, written with its bits reversed:

def crc32(data: bytes) -> int:
    crc = 0xFFFFFFFF
    for byte in data:
        crc ^= byte
        for _ in range(8):
            crc = (crc >> 1) ^ 0xEDB88320 if crc & 1 else crc >> 1
    return crc ^ 0xFFFFFFFF

This function and Python's zlib.crc32, the implementation behind real ZIP and PNG files, give identical results:

Inputcrc32() abovezlib.crc32
b"123456789"0xcbf439260xcbf43926
b"hello"0x3610a6860x3610a686
b"hellp"0xbb18ab730xbb18ab73

0xCBF43926 is the published check value for this variant, and changing a single letter changes the whole checksum. A CRC-32 detects every burst of up to 32 bits, and any damage beyond that goes unnoticed with a probability of about 1 in 4 billion. Each chunk of a PNG file ends with the CRC-32 of its contents; the endianness chapter's PNG hex dump ends with one, ba b3 4b b3. A CRC only detects: Ethernet drops a frame whose CRC fails and leaves recovery to higher layers, such as TCP retransmitting. And a CRC is not a security measure: anyone who modifies data can recompute it. Protecting against deliberate changes takes a cryptographic hash or signature.

Where error correction is used

WhereCodeWhat it does
server memorySECDED Hamming, Chipkillcorrects single bits, detects double ones
hard disksReed–Solomon, and LDPC in recent driveseach sector carries correction bytes
SSDsBCH or LDPCcorrects the growing error rate of worn flash cells
CDs and DVDsReed–Solomon (interleaved)survives scratches that wipe out thousands of consecutive bits
QR codesReed–Solomonlevels L, M, Q, H restore about 7, 15, 25 or 30 % of the code
Ethernet, ZIP, PNGCRC-32detects errors; the data is sent or read again
Wi-Fi, 5GLDPCcorrects errors on the radio link without retransmission
RAID 5XOR parity across disksrebuilds a failed disk from the others

Reed–Solomon and LDPC codes are more elaborate than Hamming codes and correct many errors per block, but they rest on the same ideas: redundancy, and a distance between valid codewords. They belong with the devices that use them, in the devices and chips level.

Takeaways

  • Redundant bits turn silent corruption into something visible: enough to detect errors, or with more, to correct them.
  • A parity bit detects any odd number of flipped bits; x86's PF flag computes byte parity on every result.
  • The Hamming distance of a code sets its power: distance d + 1 detects d errors, 2d + 1 corrects d.
  • Correcting single errors in m data bits needs r check bits with m + r + 1 ≤ 2ʳ: 3 for 4 bits, 7 for 64.
  • In a Hamming code, parity bits sit at powers of two, and the failing checks add up to the position of the bad bit: data 1011 → 0110011; flip bit 5 and the syndrome is 5.
  • SECDED adds an overall parity bit: ECC memory stores 72 bits per 64-bit word, corrects one error and detects two.
  • CRC-32 detects burst errors in Ethernet frames, ZIP and PNG files; it can be written in six lines and matches zlib.crc32. Reed–Solomon and LDPC codes correct errors in disks, SSDs, CDs, QR codes and radio links.

Foundations

  1. F.1Levels of abstraction and a short history of computers
  2. F.2Binary and hexadecimal
  3. F.3Two’s complement and signed numbers
  4. F.4Floating point (IEEE 754)
  5. F.5Characters, ASCII and Unicode
  6. F.6Endianness
  7. F.7Parity, Hamming codes and error correction
  8. F.8Units: kilo, kibi and friends