Linear block codes and Hamming codes
| Problem | Add redundant bits to a block of data so that a receiver can detect and correct bit errors |
| Devised by | Richard Hamming (1950); Marcel Golay (1949), the general construction from parity-check matrices |
| Accuracy | Corrects every single-bit error; the extended (SECDED) code also detects every double error (exhaustive table below) |
| Cost | per codeword to encode and decode; the syndrome is the XOR of the positions of the set bits |
| Read first | Entropy, divergence and mutual information |
| API | HammingCode (new, new_extended, encode, decode, n, k), HammingDecoded, HammingStatus |
Overview
A noisy channel flips bits. An error-correcting code protects data by adding redundancy in a structured way, so that the receiver can tell what was sent even when some bits arrive wrong. The vocabulary of the subject is introduced here and used throughout the chapter.
- A block code maps each block of data bits to an -bit codeword, with . Of the possible words of length , only are codewords. The rate is the fraction of transmitted bits that carry data.
- The Hamming distance between two words is the number of positions in which they differ. The minimum distance of a code is the smallest distance between two different codewords. It decides the power of the code. If fewer than bits are flipped, the result cannot be another codeword, so up to errors are always detected. And if at most bits are flipped, the received word is still closer to the codeword that was sent than to any other, so that many errors can be corrected by choosing the nearest codeword.
- A code is linear if the bitwise sum (XOR) of any two codewords is again a codeword. Arithmetic on bits is modulo 2 throughout: . (This arithmetic, on the two elements and , is called , the Galois field of two elements; the later entries use that name.) A linear code can be described by a parity-check matrix : a word is a codeword exactly when , that is, when it passes every parity check (each row of lists a set of positions whose bits must sum to 0).
- If the received word is , where has a 1 wherever an error occurred, its syndrome is . The syndrome depends only on the error, not on the codeword, and is zero when no check fails. Decoding a linear code means deducing the error from the syndrome.
The Hamming codes are the simplest nontrivial case. They have , and so correct any single error in a block, using only parity bits.
Where it is used
Any system that stores or moves bits eventually flips one, and block codes decide whether that costs a retry or a crash.
- Computer memory. Server DRAM uses ECC memory, a Hamming-type single-error-correct, double-error-detect code over each 64-bit word, so that a cosmic-ray bit flip is repaired before the program sees it.
- Storage and flash. SSD controllers and NAND flash use stronger relatives (BCH codes) on every page, because flash cells wear out and misread as they age.
- Teaching tool for coding theory. Parity checks, syndromes and the minimum distance, all introduced here, are the vocabulary of every later code in this chapter.
History
Richard Hamming, at Bell Labs in the late 1940s, was frustrated that the relay computers stopped at weekend errors instead of correcting them. He devised the codes that bear his name, published in 1950 after a patent was filed. Marcel Golay’s one-page 1949 paper had already described the code and the general parity-check construction, as well as the perfect Golay codes. Hamming codes, extended with an overall parity bit to give SECDED (single error correction, double error detection), protect computer memory to this day.
The idea
The parity-check matrix
Suppose a single bit, in position , is flipped. The error vector has a single 1, so the syndrome is simply column of . To correct every single error, the decoder must be able to tell from the syndrome which position was hit. That requires all the columns of to be different from each other, and none to be zero (a zero column would make that error invisible).
With parity checks, the columns are binary vectors of length , and there are nonzero ones. Hamming’s construction uses them all: the columns of are all the nonzero binary -vectors. This gives the longest possible code for checks, of length , with data bits: , , , and so on. The fraction of redundancy shrinks as the code grows.
The minimum distance is 3. In a linear code the minimum distance equals the smallest number of 1s in a nonzero codeword. A codeword with ones is a set of columns of that sum to zero. One column cannot (none is zero); two cannot (no two are equal); but three can, for example the columns , and . So .
A convenient ordering. Let column be the number written in binary. Then the syndrome of a single error at position is the number : the decoder computes the syndrome and flips the bit it names. Computing the syndrome is also simple, since is the sum of the columns at which has a 1: it is the XOR of the positions of the received 1 bits.
Encoding is made equally simple by placing the parity bits at the power-of-two positions , whose columns have a single 1. Put the data in the other positions, and set the parity bit at position so that bit of the syndrome is 0.
An example with the (7, 4) code. The data bits go to positions 3, 5, 6, 7.
- Parity bit 1 checks the positions whose binary form has its lowest bit set, 1, 3, 5, 7. The data bits there are , which sum to 0, so the parity bit is 0.
- Parity bit 2 checks positions 2, 3, 6, 7, with data : the parity bit is 1.
- Parity bit 4 checks positions 4, 5, 6, 7, with data : the parity bit is 0.
The codeword is . Its 1 bits are at positions 2, 3, 6 and 7, and , as it should be. Now suppose position 5 is flipped in transit. The 1 bits are then at 2, 3, 5, 6, 7, and their XOR is 5: the syndrome names the flipped bit.
Perfect codes and the extended code
Around each codeword, draw the “sphere” of words at distance at most 1 from it: the codeword itself and the words obtained by flipping one bit, words in all. Since the spheres do not overlap. There are of them, containing words: every word of length lies in exactly one sphere. Codes with this property are called perfect; no space is wasted.
Perfection has a drawback. Every received word decodes to some codeword, so the decoder never reports failure. If two bits are flipped, the received word lies in the sphere of a wrong codeword, and the decoder “corrects” a third bit, making matters worse.
The extended Hamming code appends one more bit, an overall parity check on the whole word, which raises the distance to . The decoder can then distinguish the two cases. A single error makes the overall parity odd. A double error leaves the overall parity even but gives a nonzero syndrome, which is reported as detected but not correctable:
Table 19.1. Outcomes of decoding Hamming codes with injected bit errors.
| code | bit errors | decoded correctly | detected, not corrected | decoded wrongly |
|---|---|---|---|---|
| (7,4) Hamming | 1 | 100% | 0% | 0% |
| (7,4) Hamming | 2 | 0% | 0% | 100% |
| (7,4) Hamming | 3 | 0% | 0% | 100% |
| (8,4) extended Hamming | 1 | 100% | 0% | 0% |
| (8,4) extended Hamming | 2 | 0% | 100% | 0% |
| (8,4) extended Hamming | 3 | 0% | 0% | 100% |
On a noisy channel
Figure 19.2. Hamming BER.
With hard decisions on BPSK over additive white Gaussian noise, the code gains little. Its rate of 4/7 costs 2.4 dB of energy per bit, which it barely wins back by correcting single errors: about half a decibel at . The longer code, of higher rate, gains about 1.5 dB. Real gains need longer codes with larger distance and soft decisions, the subjects of the following entries.
Algorithm
For the code with parity bits and length ; positions are numbered from 1.
Encoding.
- Place the data bits, in order, in the positions that are not powers of two. Set the parity positions to zero for the moment.
- Compute the syndrome of this word: the XOR of the positions that hold a 1.
- For each , set the parity bit at position to bit of the syndrome. This makes the syndrome of the complete word zero, because the bit at position affects only bit of the syndrome.
- For the extended code, append one more bit equal to the XOR of all the others, so that the whole word has even parity.
Decoding.
- Compute the syndrome : the XOR of the positions of the received 1 bits. For the extended code, compute also the overall parity of the received word.
- Decide:
- plain code: if , flip the bit at position ;
- extended code: if and the parity is even, there is no error. If the parity is odd, a single error has occurred: flip the bit at position , or the overall parity bit itself if . If and the parity is even, two errors have occurred: report a failure.
- Read the data bits from the positions that are not powers of two.
Both directions cost bit operations.
Implementation
let syndrome = (1..=nb).filter(|&p| word[p - 1] == 1).fold(0usize, |a, p| a ^ p);
let overall_odd = self.extended && word.iter().fold(0u8, |a, &b| a ^ b) == 1;
let status = if syndrome == 0 && !overall_odd {
HammingStatus::NoError
} else if self.extended && syndrome != 0 && !overall_odd {
HammingStatus::DoubleErrorDetected
} else if syndrome == 0 {
// Only the overall parity bit is wrong.
word[nb] ^= 1;
HammingStatus::Corrected(nb)
} else {
word[syndrome - 1] ^= 1;
HammingStatus::Corrected(syndrome - 1)
};
- Bits are
u8values 0 or 1;rranges from 2 to 20, so codes up to . - After a detected double error the returned data is the uncorrected best effort.
In practice
//! The (7,4) Hamming code and its extended (8,4) SECDED form.
use lib_jsl_information::forward_error_correction::HammingCode;
fn main() {
let code = HammingCode::new(3).unwrap();
let data = [1, 0, 1, 1];
let cw = code.encode(&data).unwrap();
println!("(7,4): data {data:?} -> codeword {cw:?}");
let mut rx = cw.clone();
rx[4] ^= 1;
let d = code.decode(&rx).unwrap();
println!("one error at index 4: {:?}, data {:?}", d.status, d.data);
let secded = HammingCode::new_extended(3).unwrap();
let cw = secded.encode(&data).unwrap();
let mut rx = cw.clone();
rx[1] ^= 1;
rx[6] ^= 1;
println!("(8,4) with two errors: {:?}", secded.decode(&rx).unwrap().status);
let big = HammingCode::new(6).unwrap();
println!("r = 6: ({}, {}) code, rate {:.3}", big.n(), big.k(), big.k() as f64 / big.n() as f64);
}
(7,4): data [1, 0, 1, 1] -> codeword [0, 1, 1, 0, 0, 1, 1]
one error at index 4: Corrected(4), data [1, 0, 1, 1]
(8,4) with two errors: DoubleErrorDetected
r = 6: (63, 57) code, rate 0.905
Strengths
- Trivial encoding and decoding with the minimum redundancy for single-error correction; SECDED adds double-error detection for one more bit.
Weaknesses
- Distance 3 or 4 only; little coding gain on noisy channels; no use of soft information.
Exercises
- Write and a generator matrix for the code, and check .
- Show that a linear code’s minimum distance is the smallest weight of a nonzero codeword.
- Prove that Hamming codes are perfect, and that the extended code has .
- Find the probability of a decoding error for the code on a binary symmetric channel with crossover .
- Show that the Hamming bound holds for every -error-correcting binary code.
Hints and answers
- For , has the seven nonzero 3-bit columns; choosing the systematic form gives , and then over GF(2).
- The distance between codewords is the weight of , which is a codeword by linearity, so the minimum distance equals the minimum weight of a nonzero codeword.
- The nonzero syndromes of a Hamming code correspond to the single-error patterns plus no error: , so spheres of radius 1 exactly tile the space (perfect). Adding an overall parity bit makes odd-weight patterns have even weight 4 or more, so .
- The code corrects any single error; a decoding error occurs when two or more of the 7 bits are flipped: for small .
- The spheres of radius around the codewords are disjoint and contain points each, so .
Further reading
- R. W. Hamming, “Error detecting and error correcting codes”, Bell System Technical Journal 29 (1950) 147–160.
- M. J. E. Golay, “Notes on digital coding”, Proceedings of the IRE 37 (1949) 657.
- S. Lin and D. J. Costello, Error Control Coding, 2nd ed., Pearson, 2004, chapters 3–4.
- F. J. MacWilliams and N. J. A. Sloane, The Theory of Error-Correcting Codes, North-Holland, 1977.