IT·08
Channels and Noise
What noise does to information, and the first defences against it: channels described by their probabilities; the binary symmetric channel and the erasure channel; how many errors a block collects, counted with the binomial distribution; how much information still gets through (0.531 bits per use when one bit in ten flips); repetition codes and the price they charge; Hamming distance and the Hamming(7,4) code that finds and fixes any single error; parity, check digits on typed numbers, checksums and CRCs that detect damage; and why one flipped bit in compressed data can ruin hundreds of thousands of bytes without any warning.
Start here
What this chapter answers
How do you describe a noisy channel? How many errors does a block of bits collect, and how likely is it to arrive intact? How much information survives the noise? How can redundancy detect errors, and how can it correct them, and at what price? Why do check digits catch the mistakes people make when typing numbers? Why does compressed data need a checksum more than plain text does?
Channels
A channel is a table of probabilities
A channel takes an input symbol and delivers an output symbol , not always the same one. It's described completely by the probabilities of each output given each input. In a memoryless channel each use is independent of the others: the noise on one bit doesn't depend on what happened to the bits before it. Real channels are only approximately memoryless (a scratch on a disc damages many bits in a row), and the chapter returns to that.
The binary symmetric channel
The simplest noisy channel carries bits and flips each one with the same probability , the crossover probability, whichever bit was sent:
It's a model, not a particular device, but it fits many: a bit on a noisy wire, a bit read back from worn storage, the sensor of chapter 7 with two states. A channel with is perfect, and one with is useless: the output is a fair coin whatever was sent. One with is perfect too, once you know to flip every bit back.
The erasure channel
Sometimes the receiver can tell that a symbol was lost. The binary erasure channel delivers each bit correctly with probability and otherwise delivers a mark "?": it never lies, but sometimes says nothing. Lost packets on a network behave like this, and a checksum is what makes them behave like this: a packet that fails its check is thrown away, so damage becomes absence. Erasures are much easier to deal with than errors, because you know where the gaps are.
How much gets through
Chapter 7 measured what a channel delivers by the mutual information between input and output. For the binary symmetric channel with equally likely inputs, the output is also equally likely, so , and whatever was sent, the uncertainty about the output is that of a coin with bias , so . Then
For , , so each use of the channel carries about 0.531 bits, and the lab measures 0.5315 from a million simulated bits. The noise doesn't just spoil one bit in ten: it costs nearly half of every bit, because the receiver doesn't know which bits were flipped. Chapter 9 shows that no choice of inputs does better, and that this number is a speed limit with a surprising property. For the erasure channel the same reasoning gives : with half the bits erased, half of each bit gets through, exactly what intuition says, because erasures announce themselves.
Errors in a block
Counting errors
Send bits through a binary symmetric channel and the number of errors follows the binomial distribution of chapter 3: each bit is an independent trial that "fails" with probability , so
with errors expected. The lab sends a million bits at and counts the errors in each byte: 43.1 % of bytes arrive clean, 38.3 % with one error, 14.8 % with two, matching the formula to the third decimal place.
Long blocks almost always have errors
The chance that a whole block arrives intact is , which is close to when is small: it depends only on the expected number of errors. A storage system with one bit error in a billion (), reading a 1 GB file (8 billion bits), expects 8 errors and reads the file perfectly only 0.03 % of the time. However good a channel is, a long enough message will be damaged, so anything that matters needs protection.
The law of large numbers (chapter 6) adds a second fact: in a long block, the fraction of errors is almost certainly close to . The noise is unpredictable bit by bit but very predictable in bulk. Chapter 9 builds on exactly this: the errors in a long block are almost always one of about typical patterns, and that count is where the in comes from.
Redundancy that protects
Repetition
The obvious protection is to say everything several times. A repetition code sends each bit three times and decodes by majority vote, so a bit is lost only if two or three of its copies are flipped:
At that's 0.028 instead of 0.1, and at it's 0.0003 instead of 0.01. Five copies do better still. The price is the rate, the fraction of transmitted bits that carry the message: for three copies, for five. To push the error probability towards zero, repetition needs more and more copies, and its rate falls towards zero too. It seemed obvious before 1948 that reliability must cost rate in this way. Chapter 9 shows it doesn't.
Distance
Hamming's idea was to look at the codewords, the blocks a code can send, and ask how different they are. The Hamming distance between two blocks of bits is the number of positions where they differ; the minimum distance of a code is the smallest distance between any two of its codewords.
Repetition-3 has two codewords, 000 and 111, at distance 3: it detects two errors or corrects one. Adding a single parity bit to a block gives distance 2: it detects one error and corrects none.
The Hamming(7,4) code
Hamming found a much more efficient way to reach distance 3. Take 4 data bits and add 3 parity bits, each the parity (the sum, modulo 2) of a different group of three data bits. In the picture, each circle must contain an even number of 1s:
The receiver recomputes the three checks. If one bit was flipped, the circles that now hold an odd number of 1s say exactly where it is: only A means ; A and B means ; all three means . Seven positions, seven non-empty patterns of failing checks, and "no check fails" for no error: three check bits describe eight situations, exactly enough. Arranged in Hamming's order (positions 1 to 7 are ), the failing checks, read as a binary number, are the position of the error: the syndrome.
The code has 16 codewords, any two at distance at least 3, so it corrects any single error in a block of 7, at rate : far better than repetition's for the same protection per block. Its limit is the same as repetition's: two errors in one block are "corrected" to the wrong codeword, adding a third error. The lab sends 1011, flips two bits, and gets back 1001.
Comparing codes
The lab sends 400,000 random bits through channels with from 0.001 to 0.2:
| Code | Rate | p = 0.01 | p = 0.1 | p = 0.2 |
|---|---|---|---|---|
| None | 1 | 0.010 | 0.099 | 0.200 |
| Repeat 3 | 0.333 | 0.00025 | 0.028 | 0.104 |
| Repeat 5 | 0.2 | 0.00001 | 0.0087 | 0.058 |
| Hamming(7,4) | 0.571 | 0.0008 | 0.067 | 0.195 |
On a good channel Hamming(7,4) cuts errors by more than ten times while sending only 75 % more bits; on a bad channel (one bit in five flipped, more than one error per block on average) it barely helps, because it was designed for one error per block. Every code here is a trade between rate and reliability, and none of them gets the error probability near zero without its rate going to zero as well. Modern codes (chapter 9) do much better, and they're built on the same idea: well-separated codewords and checks that locate errors.
Detecting errors
Parity
One parity bit, the sum modulo 2 of a block, makes the block's total even. Any odd number of errors makes it odd and shows; any even number cancels out and goes unseen. It's the cheapest possible check, a single bit, and it's an example of chapter 7's coins: the parity bit tells you nothing about any one data bit, and everything about their combination.
Check digits on typed numbers
People copying numbers make different mistakes from noisy wires. Jacobus Verhoeff's 1969 study of 12,112 errors in six-digit numbers found that 79 % changed a single digit and 10 % swapped two neighbours; everything else was rare. A check digit appended to a number is chosen to catch these.
- Adding the digits (make the total a multiple of 10) catches every single wrong digit, since one digit changing changes the total. But it catches no swaps: addition doesn't care about order.
- The Luhn check, used on payment cards, doubles every second digit (counting from the right, and adding the digits of anything over 9) before adding. Now neighbours count differently, and a swap usually changes the total. The lab finds it catches every single-digit error and 97.9 % of adjacent swaps: it misses only 09 ↔ 90, because a 0 doubled is 0 and a 9 doubled is 18, whose digits add to 9 again.
- ISBN-10 weights the ten digits 10, 9, … , 1 and makes the total divisible by 11. Because 11 is prime, changing one digit or swapping any two always changes the total modulo 11, so it catches all single errors and all swaps. The price is an eleventh symbol: when the check value is 10 it's written X.
Each check digit adds about 3.3 bits of redundancy () and lets through about one random garbling in ten; what makes it good is not catching more random damage but catching the likely damage completely.
Checksums and CRCs
For bytes, the simplest check is a sum: add the bytes and keep the total modulo 256. Like adding digits, it misses every reordering, and also any two changes that cancel (one byte up by 4, another down by 4). Fletcher's checksum (1982) and its descendant Adler-32 (Mark Adler, for zlib) add a second running sum of the first, so each byte's contribution depends on its position and swaps show.
The cyclic redundancy check treats the message's bits as the coefficients of a polynomial and keeps the remainder after dividing by a fixed generator polynomial, using arithmetic in which (addition is exclusive or, with no carries). The division is just shifting and exclusive or, cheap in hardware. Because of the algebra, a CRC with a generator of degree (with a constant term) detects every burst of errors no longer than bits, and any other damage is missed with probability about . CRC-32, with , protects Ethernet frames, zip and gzip files and PNG images.
The lab damages 20,000 blocks of 4 KB from the plays in five ways and asks each check whether the block changed. The 8-bit sum misses every swap of two bytes and every pair of changes that cancel, and about 1 in 256 to 1 in 350 random damages (73 and 57 misses, where chance predicts about 78). Adler-32 and CRC-32 miss nothing; for random damage they should miss about once in four billion blocks.
Detecting isn't correcting
A check says that something is wrong, not what. Networks pair detection with a second chance: a damaged packet fails its CRC, is thrown away (the error becomes an erasure), and is sent again. Correction costs much more redundancy than detection, so systems correct what they must (radio links, storage, deep-space probes, where sending again is slow or impossible) and detect everywhere else.
Damage in compressed data
Chapter 6's compressors remove redundancy, and redundancy is what makes damage visible and survivable. In plain text, a flipped bit spoils one character, and a reader can usually guess it from the context. In compressed data, every bit is part of a code that determines how the following bits are read, so one flip can change everything after it.
The lab flips a single bit in the middle of the plays compressed with deflate (the method inside zip and gzip) and decompresses. In all 12 trials, the decoder reported nothing wrong and produced output; the damage ranged from 3 wrong bytes to more than 600,000. Deflate often recovers, because its codes resynchronise and its blocks restart, but sometimes the output is shifted and garbled for the rest of the file, and nothing in the stream says so. An arithmetic coder, with no block boundaries, is worse still. With zlib's Adler-32 checksum added at the end, the damage was detected all 12 times.
The rule: compress, then add a check (or a correcting code designed for the channel). The order matters, and chapter 9 explains why splitting the work this way, compression to remove the source's redundancy and coding to add redundancy suited to the noise, gives up nothing in the limit.
Lab: noise, codes and checks
"""chan.py: noisy channels, simple codes and checks, for chapter 8's lab."""
import math, random, zlib
def h(p):
"""The binary entropy function, in bits."""
return 0.0 if p in (0, 1) else -p * math.log2(p) - (1 - p) * math.log2(1 - p)
def bsc(bits, p, rng):
"""A binary symmetric channel: each bit is flipped with probability p, independently."""
return [b ^ (rng.random() < p) for b in bits]
# Repetition: send each bit n times, decode by majority vote.
def rep_encode(bits, n):
return [b for b in bits for _ in range(n)]
def rep_decode(bits, n):
return [int(sum(bits[i:i + n]) > n // 2) for i in range(0, len(bits), n)]
# Hamming(7,4): 4 data bits d1..d4 and 3 parity bits; positions 1..7 are p1 p2 d1 p3 d2 d3 d4.
def ham_encode(bits):
out = []
for i in range(0, len(bits), 4):
d1, d2, d3, d4 = bits[i:i + 4]
out += [d1 ^ d2 ^ d4, d1 ^ d3 ^ d4, d1, d2 ^ d3 ^ d4, d2, d3, d4]
return out
def ham_decode(bits):
out = []
for i in range(0, len(bits), 7):
c = bits[i:i + 7]
# the syndrome: each parity check, recomputed, gives one bit of the error's position
s = (c[0] ^ c[2] ^ c[4] ^ c[6]) + 2 * (c[1] ^ c[2] ^ c[5] ^ c[6]) + 4 * (c[3] ^ c[4] ^ c[5] ^ c[6])
if s:
c[s - 1] ^= 1 # a single error is at position s: flip it back
out += [c[2], c[4], c[5], c[6]]
return out
# Check digits on typed codes.
def isbn10_check(body):
"""The ISBN-10 check character for 9 digits: weights 10 down to 2, total divisible by 11."""
r = (11 - sum((10 - i) * d for i, d in enumerate(body)) % 11) % 11
return 10 if r == 10 else r # 10 is written X
def isbn10_ok(digits):
return sum((10 - i) * d for i, d in enumerate(digits)) % 11 == 0
def luhn_ok(digits):
"""The Luhn check (payment cards): double every second digit from the right, add digits, total divisible by 10."""
total = 0
for i, d in enumerate(reversed(digits)):
if i % 2:
d = d * 2 - 9 if d > 4 else d * 2
total += d
return total % 10 == 0
def luhn_check(body):
return next(c for c in range(10) if luhn_ok(body + [c]))
def sum_ok(digits):
"""A naive check: the digits add up to a multiple of 10."""
return sum(digits) % 10 == 0
# Checksums on bytes.
def sum8(data):
return sum(data) % 256
def adler32(data):
return zlib.adler32(data)
def crc32(data):
return zlib.crc32(data)
Experiment 1: a noisy channel, counted
import math, random
from collections import Counter
from chan import bsc, h
rng = random.Random(8)
p, n = 0.1, 1_000_000
sent = [rng.getrandbits(1) for _ in range(n)]
got = bsc(sent, p, rng)
flips = sum(a != b for a, b in zip(sent, got))
print(f"sent {n:,} bits through a BSC with p = {p}: {flips:,} flipped ({flips / n:.4f})")
print("\nerrors in each 8-bit block measured binomial")
blocks = Counter(sum(a != b for a, b in zip(sent[i:i + 8], got[i:i + 8])) for i in range(0, n, 8))
for k in range(5):
print(f" {k} {'error ' if k == 1 else 'errors'} {blocks[k] / (n // 8):>23.4f}{math.comb(8, k) * p**k * (1 - p)**(8 - k):>11.4f}")
print("\nchance a block arrives with no errors, (1 - p)^n:")
for q, size in ((0.1, 8), (0.1, 100), (0.001, 100), (0.001, 1000), (1e-9, 8 * 10**9)):
print(f" p = {q:<6g} n = {size:>13,}: {(1 - q)**size:<8.3g} expected errors {q * size:g}")
pairs = Counter(zip(sent, got))
hy = h(sum(c for (x, y), c in pairs.items() if y == 1) / n)
hyx = h(flips / n)
print(f"\nH(Y) = {hy:.4f}, H(Y | X) = {hyx:.4f}, so I(X; Y) = {hy - hyx:.4f} bits per use; 1 - h(0.1) = {1 - h(0.1):.4f}")
sent 1,000,000 bits through a BSC with p = 0.1: 99,836 flipped (0.0998)
errors in each 8-bit block measured binomial
0 errors 0.4306 0.4305
1 error 0.3834 0.3826
2 errors 0.1482 0.1488
3 errors 0.0328 0.0331
4 errors 0.0046 0.0046
chance a block arrives with no errors, (1 - p)^n:
p = 0.1 n = 8: 0.43 expected errors 0.8
p = 0.1 n = 100: 2.66e-05 expected errors 10
p = 0.001 n = 100: 0.905 expected errors 0.1
p = 0.001 n = 1,000: 0.368 expected errors 1
p = 1e-09 n = 8,000,000,000: 0.000335 expected errors 8
H(Y) = 1.0000, H(Y | X) = 0.4685, so I(X; Y) = 0.5315 bits per use; 1 - h(0.1) = 0.5310
One bit in ten flipped (0.0998 of a million), and the errors in each byte follow the binomial formula closely. A block's chance of arriving clean depends only on the expected number of errors: 0.905 with 0.1 expected, 0.368 with 1, 0.0003 with 8, whether that's 100 bits on a poor channel or 8 billion on an excellent one. The measured mutual information, 0.5315 bits per use, agrees with .
Experiment 2: repetition against Hamming
import random
from chan import bsc, rep_encode, rep_decode, ham_encode, ham_decode
rng = random.Random(8)
data = [rng.getrandbits(1) for _ in range(400_000)]
codes = {"none": (lambda b: b, lambda b: b, 1),
"repeat 3": (lambda b: rep_encode(b, 3), lambda b: rep_decode(b, 3), 1 / 3),
"repeat 5": (lambda b: rep_encode(b, 5), lambda b: rep_decode(b, 5), 1 / 5),
"Hamming(7,4)": (ham_encode, ham_decode, 4 / 7)}
print(f"{'code':<14}{'rate':>6}" + "".join(f"{'p = ' + str(p):>12}" for p in (0.001, 0.01, 0.05, 0.1, 0.2)))
for name, (enc, dec, rate) in codes.items():
row = []
for p in (0.001, 0.01, 0.05, 0.1, 0.2):
out = dec(bsc(enc(data), p, rng))
row.append(sum(a != b for a, b in zip(data, out)) / len(data))
print(f"{name:<14}{rate:>6.3f}" + "".join(f"{e:>12.2e}" for e in row))
print("\nrepeat 3 by formula, 3p^2 - 2p^3: " + " ".join(f"{3 * p * p - 2 * p**3:.2e}" for p in (0.001, 0.01, 0.05, 0.1, 0.2)))
# Hamming(7,4) corrects every single error: check all 16 messages and all 7 positions
fixed = 0
for m in range(16):
msg = [(m >> k) & 1 for k in range(4)]
for pos in range(7):
c = ham_encode(msg); c[pos] ^= 1
fixed += ham_decode(c) == msg
print(f"Hamming(7,4): {fixed} of 112 single errors corrected")
c = ham_encode([1, 0, 1, 1]); c[1] ^= 1; c[5] ^= 1
print(f"two errors in one block: sent 1011, decoded {''.join(map(str, ham_decode(c)))}")
code rate p = 0.001 p = 0.01 p = 0.05 p = 0.1 p = 0.2
none 1.000 9.92e-04 9.97e-03 5.04e-02 9.94e-02 2.00e-01
repeat 3 0.333 0.00e+00 2.53e-04 7.19e-03 2.80e-02 1.04e-01
repeat 5 0.200 0.00e+00 1.00e-05 1.19e-03 8.73e-03 5.81e-02
Hamming(7,4) 0.571 1.25e-05 8.00e-04 1.96e-02 6.70e-02 1.95e-01
repeat 3 by formula, 3p^2 - 2p^3: 3.00e-06 2.98e-04 7.25e-03 2.80e-02 1.04e-01
Hamming(7,4): 112 of 112 single errors corrected
two errors in one block: sent 1011, decoded 1001
The measured error rates match the formula ( for three copies); at , the repetition codes made no errors in 400,000 bits, where the formula predicts about one for three copies. Hamming(7,4) fixes all 112 single errors (16 messages, 7 positions), and turns two errors into three.
Experiment 3: check digits against typing errors
import random
from chan import isbn10_check, isbn10_ok, luhn_check, luhn_ok, sum_ok
rng = random.Random(8)
def sum_check(body):
return (-sum(body)) % 10
schemes = {"digits add to 0 mod 10": (sum_check, sum_ok, 15),
"Luhn (payment cards)": (luhn_check, luhn_ok, 15),
"ISBN-10 (mod 11)": (isbn10_check, isbn10_ok, 9)}
print(f"{'check':<24}{'single-digit errors caught':>28}{'adjacent swaps caught':>24}")
for name, (check, ok, length) in schemes.items():
single = [0, 0]; swap = [0, 0]
for _ in range(2000):
body = [rng.randrange(10) for _ in range(length)]
code = body + [check(body)]
for i in range(len(code)):
for d in range(11 if i == len(code) - 1 and length == 9 else 10):
if d != code[i]:
bad = code[:i] + [d] + code[i + 1:]
single[0] += not ok(bad); single[1] += 1
for i in range(len(code) - 1):
if code[i] != code[i + 1]:
bad = code[:i] + [code[i + 1], code[i]] + code[i + 2:]
swap[0] += not ok(bad); swap[1] += 1
print(f"{name:<24}{single[0] / single[1]:>27.2%} {swap[0] / swap[1]:>23.2%}")
missed = sorted({(a, b) for a in range(10) for b in range(10) if a != b and luhn_ok([a, b, luhn_check([a, b])]) and luhn_ok([b, a, luhn_check([a, b])])})
print("adjacent swaps Luhn never catches:", missed)
check single-digit errors caught adjacent swaps caught
digits add to 0 mod 10 100.00% 0.00%
Luhn (payment cards) 100.00% 97.91%
ISBN-10 (mod 11) 100.00% 100.00%
adjacent swaps Luhn never catches: [(0, 9), (9, 0)]
All three catch every single wrong digit; only the weighted checks catch swaps. Luhn misses exactly the swaps of 0 and 9, and ISBN-10's prime modulus misses none.
Experiment 4: checksums against damage
import random
from pathlib import Path
from chan import sum8, adler32, crc32
rng = random.Random(8)
text = Path("shakespeare.txt").read_bytes()
def flip_bit(b):
i = rng.randrange(len(b) * 8); b[i // 8] ^= 1 << (i % 8)
def swap_bytes(b):
while True:
i = rng.randrange(len(b) - 1)
if b[i] != b[i + 1]:
b[i], b[i + 1] = b[i + 1], b[i]; return
def cancel(b): # one byte up by 4, another down by 4: the total is unchanged
i, j = rng.sample([k for k in range(len(b)) if 4 <= b[k] < 252], 2)
b[i] += 4; b[j] -= 4
def burst(b): # 32 bits in a row replaced by random bits
i = rng.randrange(len(b) - 4); b[i:i + 4] = rng.randbytes(4)
def garbage(b): # the whole block replaced by random bytes
b[:] = rng.randbytes(len(b))
damage = {"one bit flipped": flip_bit, "two bytes swapped": swap_bytes, "+4 and -4": cancel,
"32-bit burst": burst, "all random": garbage}
checks = {"8-bit sum": sum8, "Adler-32": adler32, "CRC-32": crc32}
trials = 20_000
print(f"undetected damage in {trials:,} damaged 4 KB blocks of the plays\n{'damage':<20}" + "".join(f"{c:>12}" for c in checks))
for dname, hurt in damage.items():
missed = dict.fromkeys(checks, 0)
for _ in range(trials):
start = rng.randrange(len(text) - 4096)
good = text[start:start + 4096]
bad = bytearray(good); hurt(bad)
if bytes(bad) == good:
continue
for cname, f in checks.items():
missed[cname] += f(bytes(bad)) == f(good)
print(f"{dname:<20}" + "".join(f"{missed[c]:>12,}" for c in checks))
print(f"\nexpected misses for random damage: 8-bit sum {trials / 256:.0f}, a 32-bit check {trials / 2**32:.6f}")
undetected damage in 20,000 damaged 4 KB blocks of the plays
damage 8-bit sum Adler-32 CRC-32
one bit flipped 0 0 0
two bytes swapped 20,000 0 0
+4 and -4 20,000 0 0
32-bit burst 73 0 0
all random 57 0 0
expected misses for random damage: 8-bit sum 78, a 32-bit check 0.000005
A sum is blind to order and to changes that cancel; its random misses (73 and 57) are around the 1 in 256 that chance predicts. The 32-bit checks caught every damaged block.
Experiment 5: one bit in compressed data
import random, zlib
from pathlib import Path
rng = random.Random(8)
text = Path("shakespeare.txt").read_bytes()
def deflate(data, wbits):
c = zlib.compressobj(9, zlib.DEFLATED, wbits); return c.compress(data) + c.flush()
raw, wrapped = deflate(text, -15), deflate(text, 15) # raw deflate, and deflate with zlib's Adler-32 at the end
print(f"plays {len(text):,} bytes; raw deflate {len(raw):,}; with zlib's header and checksum {len(wrapped):,}")
print("\none bit flipped in the middle third of the raw deflate stream (no checksum):")
outcomes = {"decoder error": 0, "decoded, wrong": 0, "decoded, right": 0}
for t in range(12):
pos = rng.randrange(len(raw) // 3, 2 * len(raw) // 3)
bad = bytearray(raw); bad[pos] ^= 1 << rng.randrange(8)
try:
out = zlib.decompressobj(-15).decompress(bytes(bad))
except zlib.error as e:
outcomes["decoder error"] += 1
print(f" byte {pos:>7,}: decoder error ({e})"); continue
first = next((i for i, (a, b) in enumerate(zip(out, text)) if a != b), min(len(out), len(text)))
wrong = sum(a != b for a, b in zip(out, text)) + abs(len(out) - len(text))
outcomes["decoded, right" if wrong == 0 else "decoded, wrong"] += 1
print(f" byte {pos:>7,}: decoded {len(out):>9,} bytes, first wrong at {first:>9,}, {wrong:>9,} bytes wrong")
print(" ", outcomes)
print("\nthe same damage with zlib's checksum:")
caught = 0
for t in range(12):
pos = rng.randrange(len(wrapped) // 3, 2 * len(wrapped) // 3)
bad = bytearray(wrapped); bad[pos] ^= 1 << rng.randrange(8)
try:
zlib.decompress(bytes(bad)); print(" NOT detected")
except zlib.error as e:
caught += 1
print(f" {caught} of 12 detected")
print("\nand in the plain text, one flipped bit is one wrong byte.")
plays 1,115,394 bytes; raw deflate 434,696; with zlib's header and checksum 434,702
one bit flipped in the middle third of the raw deflate stream (no checksum):
byte 204,327: decoded 1,115,394 bytes, first wrong at 524,238, 5 bytes wrong
byte 243,298: decoded 1,115,394 bytes, first wrong at 624,517, 84 bytes wrong
byte 195,522: decoded 1,115,394 bytes, first wrong at 501,998, 520 bytes wrong
byte 167,228: decoded 1,115,397 bytes, first wrong at 431,017, 616,565 bytes wrong
byte 209,763: decoded 1,115,394 bytes, first wrong at 538,213, 7 bytes wrong
byte 249,941: decoded 1,115,394 bytes, first wrong at 641,881, 123 bytes wrong
byte 265,257: decoded 1,115,394 bytes, first wrong at 683,508, 118 bytes wrong
byte 263,683: decoded 1,115,394 bytes, first wrong at 679,045, 10 bytes wrong
byte 274,654: decoded 1,115,396 bytes, first wrong at 707,806, 338,928 bytes wrong
byte 250,459: decoded 1,115,394 bytes, first wrong at 643,339, 93 bytes wrong
byte 272,063: decoded 1,115,394 bytes, first wrong at 701,083, 3 bytes wrong
byte 150,138: decoded 1,115,394 bytes, first wrong at 386,110, 3 bytes wrong
{'decoder error': 0, 'decoded, wrong': 12, 'decoded, right': 0}
the same damage with zlib's checksum:
12 of 12 detected
and in the plain text, one flipped bit is one wrong byte.
Twelve single-bit flips, twelve silent wrong answers, from 3 bytes to over half the file. With the checksum, all twelve were caught.
Worked examples
A packet over a good link
Decoding Hamming(7,4) by hand
Information through an erasure channel
Exercises
Practice
- A channel flips bits with probability 0.05. What's the chance that a byte arrives with no errors? With exactly one?
- Find the Hamming distance between 1011001 and 1001101.
- A code has minimum distance 5. How many errors can it detect? Correct?
- What's the rate of a code that sends 11 data bits in blocks of 15?
- Does the digit-sum check catch the error 4721 → 4712?
- Compute for , 0.5 and 0.9, and explain the last.
- Why does compressed data need a checksum more than plain text?
Answers
- ; .
- 2 (the third and fifth positions differ).
- Detect 4; correct 2.
- (the Hamming(15,11) code).
- No: it's a swap, and the digits' total doesn't change.
- 1, 0 and : flipping 90 % is as good as flipping 10 %, once you know to flip the output back.
- Compression removes the redundancy that makes damage visible; one flipped bit can garble much of the rest without any sign.
Harder
- Show that a single parity bit appended to data bits gives a code of minimum distance 2.
- For repetition-5, write the probability of a wrong majority and evaluate it at ; compare with the lab's 0.0087.
- Hamming(7,4) at : what's the probability that a block has two or more errors? Why is the lab's bit error rate (0.0008) less than half of that?
- Prove that the ISBN-10 check catches every swap of two adjacent digits.
- A disk returns an unreadable sector rather than wrong data when its internal code fails. Which channel model does a storage system built on such disks see, and why does it make redundancy across disks (RAID) easier?
Answers
- Two different data blocks differ in at least one data bit; if they differ in an odd number, their parity bits differ too, giving distance at least 2; if in an even number (at least 2), the distance is already 2. Blocks differing in one data bit and the parity bit are at distance exactly 2, so the minimum is 2.
- Three or more of five copies flipped: . At the three terms are 0.0081, 0.00045 and 0.00001, about 0.00856 in all, close to the measured 0.0087.
- . A block with two errors is decoded with three wrong bits out of 7, but only some of them are data bits, and the rate counts wrong data bits per data bit: on average about of the block's 4 data bits per failed block, so the bit error rate is roughly .
- Digits and in positions with weights and contribute ; swapped, . The difference is , which isn't a multiple of 11 for different digits, so the total changes modulo 11.
- An erasure channel: the system knows which sector is missing. With known positions, a single parity disk can rebuild any one lost disk (the missing block is the exclusive or of the others), whereas locating an unknown wrong disk would need more redundancy.
Challenge
- Hamming codes exist for blocks of bits with check bits. Explain why check bits can correct a single error in at most bits, and find the rate of the code with . What happens to the error probability per block as grows, for a fixed ?
Discussion
The checks give syndromes; one must mean "no error" and each of the positions needs its own, so , with Hamming codes meeting it exactly (they're "perfect"). With , and the rate is . But the code still corrects only one error per block, and a block of 1023 bits at expects about 10 errors, so almost every block fails. Longer Hamming codes have higher rates and worse reliability: Hamming codes alone can't approach both high rate and low error, and chapter 9 explains what can.
In real life
Misconceptions and limits
The model to keep
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "A channel that flips 10 % of bits delivers 90 % of the information." | It delivers 0.531 bits per bit: the receiver doesn't know which bits flipped. | How much gets through; Experiment 1 |
| "A very good channel doesn't need protection." | At one error in a billion, a 1 GB read is error-free 0.03 % of the time. | Long blocks almost always have errors |
| "More check bits always mean more protection." | Hamming(1023,1013) has more check bits than Hamming(7,4) but fails almost every block at p = 0.01. | Challenge 13 |
| "Hamming(7,4) handles two errors badly but harmlessly." | It "corrects" them into a third error: 1011 came back as 1001. | Experiment 2 |
| "Any check digit catches swapped digits." | Adding the digits catches none; Luhn misses 09 ↔ 90. | Experiment 3 |
| "A checksum is a checksum." | An 8-bit sum missed every byte swap; CRC-32 missed nothing. | Experiment 4 |
| "A decompressor will report damaged input." | Deflate decoded every one of 12 damaged streams without complaint. | Experiment 5 |
| "Erasures and errors cost the same." | 10 % erased leaves 0.9 bits per use; 10 % flipped leaves 0.531. | Worked example, erasure channel |
Limits and trade-offs
- Real noise isn't memoryless. Scratches, radio fades and failing cells damage bits in bursts. Codes designed for independent errors fail on bursts; interleaving (spreading each codeword's bits apart) and codes over bytes (Reed–Solomon) handle them.
- A check can be fooled on purpose. CRCs and sums protect against accidents, not attackers: anyone can change data and recompute the check. Protection against tampering needs cryptographic hashes and signatures.
- Detection needs a second chance. Detecting damage only helps if the data can be sent or read again, or recovered from a copy; otherwise you need correction, which costs more redundancy.
Revision sheet
Key ideas
- Channel: the probabilities ; memoryless if uses are independent.
- Binary symmetric channel: each bit flipped with probability ; with equally likely inputs (0.531 for ).
- Binary erasure channel: each bit lost (marked) with probability ; .
- Errors in a block: binomial, mean ; .
- Rate: data bits per transmitted bit.
- Repetition-3: rate , .
- Minimum distance : detects errors, corrects .
- Hamming(7,4): 4 data bits, 3 parity bits, distance 3; the syndrome is the error's position.
- Check digits: weighted sums catch swaps; ISBN-10 (mod 11) catches all single errors and swaps; Luhn misses 09 ↔ 90.
- CRC: remainder of polynomial division by exclusive or; catches every burst up to its degree.
- Compressed data: no redundancy left, so one bit can ruin the rest: always add a check.
Glossary
- Channel: a model of transmission, giving the probability of each output for each input.
- Memoryless channel: a channel whose uses are independent of each other.
- Binary symmetric channel: a channel that flips each bit with the same probability, whichever bit was sent.
- Crossover probability: the probability that a binary symmetric channel flips a bit.
- Binary erasure channel: a channel that delivers each bit correctly or marks it as lost, never wrong.
- Rate (of a code): the fraction of transmitted bits that carry the message.
- Repetition code: a code that sends each bit several times and decodes by majority.
- Hamming distance: the number of positions in which two blocks differ.
- Minimum distance: the smallest Hamming distance between two codewords of a code.
- Parity bit: a bit making the number of 1s in a block even (or odd).
- Hamming(7,4) code: the code sending 4 data bits with 3 parity bits, correcting any single error.
- Syndrome: the pattern of failed checks, which locates the error in a Hamming code.
- Check digit: a digit appended to a number so that common mistakes in copying it can be detected.
- Checksum: a short value computed from data to detect accidental changes.
- Cyclic redundancy check (CRC): a checksum given by the remainder of dividing the data, as a polynomial, by a generator polynomial.
- Burst error: damage to several bits in a row.