Information Theory CompanionInformation Theory · Companion
0 / 0

Workbench / Information Theory Companion

B1·08

Channels and Noise

Around chapter 8: how channels, error counts, codes and checks connect the book; three other ways to see them; what the chapter simplifies (Adler-32 is weak on short messages, a CRC is no defence against someone who wants to change the data, and 1 − h(p) is a ceiling that simple codes come nowhere near); how zlib computes Adler-32 with one division per 5,552 bytes; four debugging drills; and interview questions.

6 topics · ~18 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Conditional probability (chapter 3) → a channel is the table p(y∣x).
  • Binary symmetric channel + mutual information (chapter 7) → 1−h(p) bits per use with equally likely inputs → capacity (chapter 9).
  • Erasure channel: damage you can see costs less (1−ε); a checksum turns errors into erasures.
  • Binomial count (chapter 3) → errors in a block, P(none)≈e−np → long messages need protection.
  • Law of large numbers (chapter 6) → typical error patterns, about 2nh(p) of them → why h(p) is subtracted (chapter 9).
  • Redundancy → repetition (rate falls with errors) → distance → Hamming(7,4), SECDED, Reed–Solomon.
  • Detection: parity, check digits, sums, Adler-32, CRCs → designed for the likely damage.
  • Compression (chapters 5 and 6) removes redundancy → compressed data is fragile → check after compressing; source and channel coding separate (chapter 9).

Explain it differently

A noisy phone line. On a bad line you spell your name: "B for bravo, O for oscar". The spelling alphabet adds redundancy so different letters sound very different: it increases the distance between codewords, so a garbled word is still nearer to the right one. Saying everything twice is repetition; the spelling alphabet is a better code.

Seats on a train. Think of codewords as seats in a carriage and errors as passengers drifting a seat or two. If occupied seats are at least three apart, anyone who drifted one seat is still nearest their own: correction. If they're two apart, you can see someone is out of place, but not whose seat they left: detection. Packing more passengers (a higher rate) means seats closer together, and less tolerance for drift.

The sealed envelope. A checksum is a seal on an envelope: it shows that something was disturbed, not what the letter said. And it only works if the envelope was sealed before anything could happen to the letter: a seal applied after tampering proves nothing (drill D4).

Gaps and misconceptions

What the chapter oversimplifies

1. "Adler-32 and CRC-32 both missed nothing", but Adler-32 is weak on short messages. The chapter's lab used 4 KB blocks. On short messages, Adler-32's sums can't spread over all 32 bits:

Python
import random, zlib
from collections import Counter

rng = random.Random(8)
LETTERS = bytes(97 + b % 26 for b in range(256))          # any byte becomes a lowercase letter (nearly evenly)
n = 1_000_000
for length in (8, 64, 1024):
    msgs = {rng.randbytes(length).translate(LETTERS) for _ in range(n)}
    for name, f in (("Adler-32", zlib.adler32), ("CRC-32", zlib.crc32)):
        values = Counter(map(f, msgs))
        pairs = sum(c * (c - 1) // 2 for c in values.values())
        print(f"{length:>5}-letter messages, {name:<8}: {len(values):>9,} different values, {pairs:>11,} colliding pairs")
    print(f"      a perfect 32-bit check: about {len(msgs) ** 2 / 2 / 2**32:.0f} colliding pairs among {len(msgs):,} messages")
Text
    8-letter messages, Adler-32:    31,251 different values,  37,536,555 colliding pairs
    8-letter messages, CRC-32  :   999,898 different values,         101 colliding pairs
      a perfect 32-bit check: about 116 colliding pairs among 999,999 messages
   64-letter messages, Adler-32:   614,193 different values,     606,521 colliding pairs
   64-letter messages, CRC-32  :   999,878 different values,         122 colliding pairs
      a perfect 32-bit check: about 116 colliding pairs among 1,000,000 messages
 1024-letter messages, Adler-32:   991,117 different values,       8,948 colliding pairs
 1024-letter messages, CRC-32  :   999,886 different values,         114 colliding pairs
      a perfect 32-bit check: about 116 colliding pairs among 1,000,000 messages

A million random 8-letter messages produce only 31,251 different Adler-32 values and over 37 million colliding pairs, where a good 32-bit check (CRC-32 here) gives about the 116 that chance predicts. Even at 1,024 letters Adler-32 has 8,948 colliding pairs. The reason is in its design: both sums start small and grow with the message, so short messages use a small corner of the possible values (the walkthrough measures it). Mark Adler chose it for zlib because it's faster than a CRC and zlib streams are usually long; for short messages (network packets, database keys, small records), use a CRC. RFC 3309 (2002) replaced Adler-32 with CRC-32c in the SCTP protocol for exactly this reason.

2. "A CRC detects damage", but not damage someone intends. A CRC is linear: the CRC of the exclusive or of messages is the exclusive or of their CRCs (for equal lengths). That makes it easy to change a message and fix its CRC:

Python
import random, zlib

rng = random.Random(8)
a, b, c = (rng.randbytes(100) for _ in range(3))
xor = lambda *ms: bytes(map(lambda t: t[0] ^ t[1] ^ t[2], zip(*ms)))
print("CRC of a xor b xor c equals the xor of their CRCs:", zlib.crc32(xor(a, b, c)) == zlib.crc32(a) ^ zlib.crc32(b) ^ zlib.crc32(c))

def forge(msg, target):
    """Append 4 bytes to msg so that its CRC-32 equals target: solve 32 linear equations over bits."""
    base = zlib.crc32(msg + bytes(4))
    effect = []                                    # what flipping each of the 32 appended bits does to the CRC
    for i in range(32):
        tail = bytearray(4); tail[i // 8] |= 1 << (i % 8)
        effect.append(zlib.crc32(msg + bytes(tail)) ^ base)
    want, rows = base ^ target, [(e, 1 << i) for i, e in enumerate(effect)]
    chosen, pivots = 0, {}
    for e, mask in rows:                           # Gaussian elimination, with exclusive or for subtraction
        for bit, (pe, pm) in pivots.items():
            if e >> bit & 1:
                e, mask = e ^ pe, mask ^ pm
        if e:
            bit = e.bit_length() - 1
            for k, (pe, pm) in list(pivots.items()):
                if pe >> bit & 1:
                    pivots[k] = (pe ^ e, pm ^ mask)
            pivots[bit] = (e, mask)
    for bit, (pe, pm) in pivots.items():
        if want >> bit & 1:
            chosen ^= pm
    return msg + chosen.to_bytes(4, "little")

original = b"Transfer 100 to account 4711. "
target = zlib.crc32(original + b"OK!!")
forged = forge(b"Transfer 900 to account 4711. ", target)
print(f"original {original + b'OK!!'!r} crc {target:08x}")
print(f"forged   {forged!r} crc {zlib.crc32(forged):08x}")
Text
CRC of a xor b xor c equals the xor of their CRCs: True
original b'Transfer 100 to account 4711. OK!!' crc ca3c500c
forged   b'Transfer 900 to account 4711. 9B\xd3\x04' crc ca3c500c

The forged message says 900 instead of 100 and has the same CRC-32 as the original, by choosing 4 appended bytes: 32 linear equations in 32 unknown bits, solved in microseconds. (If the CRC must stay at a fixed place, an attacker can still choose 4 bytes anywhere they control.) Every check in the chapter is like this: it protects against accidents, whose patterns don't depend on the data. Against an adversary, use a cryptographic hash (SHA-256) when the expected value comes from a trusted source, and a message authentication code (HMAC) or signature when it travels with the data.

3. "1−h(p) bits get through", but not with these codes. The chapter's codes come nowhere near it:

Python
import random
from chan import bsc, h, rep_encode, rep_decode, ham_encode, ham_decode

rng = random.Random(8)
data = [rng.getrandbits(1) for _ in range(200_000)]
codes = {"repeat 3": (lambda b: rep_encode(b, 3), lambda b: rep_decode(b, 3), 1 / 3),
         "Hamming(7,4)": (ham_encode, ham_decode, 4 / 7)}
print(f"{'p':<6}{'1 - h(p)':>10}" + "".join(f"{n + ': rate, errors left':>36}" for n in codes))
for p in (0.01, 0.05, 0.1):
    cells = []
    for enc, dec, rate in codes.values():
        err = sum(x != y for x, y in zip(data, dec(bsc(enc(data), p, rng)))) / len(data)
        cells.append(f"{rate:.3f}, {err:.5f}")
    print(f"{p:<6}{1 - h(p):>10.3f}" + "".join(f"{c:>36}" for c in cells))
Text
p       1 - h(p)         repeat 3: rate, errors left     Hamming(7,4): rate, errors left
0.01       0.919                      0.333, 0.00027                      0.571, 0.00093
0.05       0.714                      0.333, 0.00742                      0.571, 0.01896
0.1        0.531                      0.333, 0.02813                      0.571, 0.06718

At p=0.01, the channel can in principle carry 0.919 bits per use. Repetition-3 delivers 0.333 and still leaves 27 errors in 100,000 bits; Hamming(7,4) delivers 0.571 and leaves 93. At p=0.1 the gap is worse: both codes leave errors in the percent range at rates below 0.531. 1−h(p) is the mutual information through the channel, a ceiling on what any code can achieve, not what a code achieves. Chapter 9 shows that codes reaching close to it with errors close to zero exist, but they need long blocks, and practical ones (turbo and LDPC codes) arrived only in the 1990s.

Common misconceptions

Misconception What's actually true Where it's shown
"Any 32-bit checksum spreads over 2³² values." 8-letter messages got 31,251 Adler-32 values; CRC-32 behaved like chance. What the chapter oversimplifies, point 1
"A valid CRC means the data wasn't altered." A changed amount was given a matching CRC by choosing 4 bytes. What the chapter oversimplifies, point 2
"Hamming(7,4) gets close to the channel's limit." At p = 0.01 it runs at 0.571 with errors left; the limit is 0.919 with none. What the chapter oversimplifies, point 3
"zlib computes a modulo for every byte." It delays the modulo for 5,552 bytes, the most before the sums could overflow. Code walkthrough
"A Hamming decoder either works or crashes." With its check bits in the wrong order, it 'corrected' as many bits as it broke. Drill D1
"If the CRC matches, the file is fine; if not, it's damaged." Read as a signed number, half of undamaged files failed. Drill D2
"A check digit routine that accepts test cards is correct." It accepted every 16-digit number and rejected 9 in 10 valid 15-digit ones. Drill D3
"Data that passes its CRC was transmitted correctly." A CRC computed after the damage made 102 corrupt files pass. Drill D4

Theoretical gaps: the ideas behind the chapter

  • Error detection as hypothesis testing. A receiver deciding "damaged or not" is choosing between hypotheses, and a check of r bits fails to notice random damage with probability about 2−r. Undetected errors are what's left when the damage happens to produce another valid codeword, so the probability depends on the code's weight distribution, which is how CRC polynomials are chosen for particular message lengths (Philip Koopman's catalogue of CRC polynomials, from 2004 on).
  • Channels with memory. The Gilbert–Elliott model (1960, 1963) used in the exercises' P2 has a hidden good and bad state; its capacity is more than that of a memoryless channel with the same average error rate, because the memory is a structure a code can exploit, and interleaving throws that structure away in exchange for simplicity.
  • The end-to-end argument. Jerome Saltzer, David Reed and David Clark (1984) argued that a function such as checking data integrity can be completely implemented only at the ends of a system, with the parts in the middle offering performance, not guarantees. Drill D4 is the argument in miniature.

Applying it

Code walkthrough

zlib's Adler-32 keeps two sums: adler, one plus the sum of the bytes, and sum2, the sum of the running values of adler, both modulo 65,521. Excerpt from adler32.c in zlib 1.3.1 (at github.com/madler/zlib), the main loop of adler32_z:

C
#define BASE 65521U     /* largest prime smaller than 65536 */
#define NMAX 5552
/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */

#define DO1(buf,i)  {adler += (buf)[i]; sum2 += adler;}
...
    /* do length NMAX blocks -- requires just one modulo operation */
    while (len >= NMAX) {
        len -= NMAX;
        n = NMAX / 16;          /* NMAX is divisible by 16 */
        do {
            DO16(buf);          /* 16 sums unrolled */
            buf += 16;
        } while (--n);
        MOD(adler);
        MOD(sum2);
    }

The sums are the chapter's "sum plus a sum of sums": adler alone is a plain checksum, and sum2 adds each byte once for every byte after it, so a byte's contribution depends on its position and swaps show. The modulus is a prime, 65,521, for the same reason as ISBN-10's 11: changes that are multiples of a composite modulus's factors would cancel. The speed trick is NMAX: a division is slow, so zlib adds up to 5,552 bytes before reducing, the largest count for which sum2 can't overflow 32 bits even if every byte is 255. DO16 unrolls the loop 16 times. Measured:

Python
import zlib
from pathlib import Path

BASE, NMAX = 65521, 5552
def adler32(data):
    """zlib's method: two running sums, with the modulo delayed to once per NMAX bytes."""
    a, b = 1, 0
    for start in range(0, len(data), NMAX):
        for byte in data[start:start + NMAX]:
            a += byte; b += a
        a %= BASE; b %= BASE
    return b << 16 | a

largest = max(n for n in range(1, 10_000) if 255 * n * (n + 1) // 2 + (n + 1) * (BASE - 1) <= 2**32 - 1)
print("largest n before the sums can overflow 32 bits:", largest)
text = Path("shakespeare.txt").read_bytes()
for msg in (b"", b"a", b"Wikipedia", text):
    print(f"{len(msg):>9,} bytes: ours {adler32(msg):08x}  zlib {zlib.adler32(msg):08x}")
print(f"8 lowercase letters: the first sum lies in {1 + 8 * 97:,} to {1 + 8 * 122:,}, the second in {8 + 36 * 97:,} to {8 + 36 * 122:,}")
Text
largest n before the sums can overflow 32 bits: 5552
        0 bytes: ours 00000001  zlib 00000001
        1 bytes: ours 00620062  zlib 00620062
        9 bytes: ours 11e60398  zlib 11e60398
1,115,394 bytes: ours f7039174  zlib f7039174
8 lowercase letters: the first sum lies in 777 to 977, the second in 3,500 to 4,400

The Python version, with the same delayed modulo, matches zlib on the empty input (1, from adler's starting value), a single byte, the word "Wikipedia" and the whole plays, and the overflow condition in the comment does give 5,552. The last line explains point 1 above: for 8 lowercase letters the two halves of the checksum can only take about 200 and 900 values out of 65,536 each.

Read it yourself

Using the code above: why does adler start at 1 rather than 0, and what would go wrong if BASE were 65,536 (so the modulo were just keeping the low 16 bits)?

Debugging drills

D1. A Hamming code that does nothing

A Hamming(7,4) decoder leaves as many errors as sending the data unprotected: 0.00100 of bits wrong at p=0.001, 0.01026 at p=0.01.

Python
import random
from chan import bsc, ham_encode

def ham_decode_buggy(bits):
    out = []
    for i in range(0, len(bits), 7):
        c = bits[i:i + 7]
        s = 4 * (c[0] ^ c[2] ^ c[4] ^ c[6]) + 2 * (c[1] ^ c[2] ^ c[5] ^ c[6]) + (c[3] ^ c[4] ^ c[5] ^ c[6])
        if s:
            c[s - 1] ^= 1
        out += [c[2], c[4], c[5], c[6]]
    return out

rng = random.Random(8)
data = [rng.getrandbits(1) for _ in range(200_000)]
for p in (0.001, 0.01):
    got = ham_decode_buggy(bsc(ham_encode(data), p, rng))
    print(f"p = {p}: {sum(a != b for a, b in zip(data, got)) / len(data):.5f} of data bits wrong after 'correction'")
Text
p = 0.001: 0.00100 of data bits wrong after 'correction'
p = 0.01: 0.01026 of data bits wrong after 'correction'

D2. Half the good files fail their check

A file format stores a CRC-32 in its first 4 bytes. Undamaged files fail the check almost half the time.

Python
import random, struct, zlib

def write(data):
    return struct.pack(">I", zlib.crc32(data)) + data       # 4-byte CRC, then the data

def check(blob):
    (stored,) = struct.unpack(">i", blob[:4])                # read the CRC back
    return stored == zlib.crc32(blob[4:])

rng = random.Random(8)
files = [rng.randbytes(rng.randrange(100, 5000)) for _ in range(1000)]
bad = sum(not check(write(f)) for f in files)
print(f"{bad} of {len(files)} undamaged files fail their check")
Text
479 of 1000 undamaged files fail their check

D3. A card number check that rejects valid cards

A Luhn routine accepts every 16-digit test card but rejects 9 in 10 valid 15-digit numbers.

Python
import random

def luhn_ok_buggy(number):
    digits = [int(c) for c in number]
    total = 0
    for i, d in enumerate(digits):                           # double every second digit
        if i % 2 == 0:
            d = d * 2 - 9 if d > 4 else d * 2
        total += d
    return total % 10 == 0

def luhn_make(body):                                         # a correct generator, as the card issuer uses
    for c in "0123456789":
        digits = [int(x) for x in reversed(body + c)]
        if sum((d * 2 - 9 if d > 4 else d * 2) if i % 2 else d for i, d in enumerate(digits)) % 10 == 0:
            return body + c

rng = random.Random(8)
for length in (16, 15):
    valid = [luhn_make("".join(rng.choice("0123456789") for _ in range(length - 1))) for _ in range(10_000)]
    print(f"{length}-digit valid numbers accepted: {sum(map(luhn_ok_buggy, valid)) / len(valid):.1%}")
Text
16-digit valid numbers accepted: 100.0%
15-digit valid numbers accepted: 10.1%

D4. Corrupt files with valid CRCs

An upload service computes a CRC for each file, and the storage service checks it on arrival. Not one upload in 5,000 fails, yet audits find files with wrong bits.

Python
import random, zlib

rng = random.Random(8)

def faulty_buffer(data):
    """A copy through memory with a fault: about one copy in 50 gets one bit flipped."""
    data = bytearray(data)
    if rng.random() < 0.02:
        i = rng.randrange(len(data) * 8); data[i // 8] ^= 1 << (i % 8)
    return bytes(data)

def send(data):
    staged = faulty_buffer(data)                 # the upload service copies the file into its buffer...
    return staged, zlib.crc32(staged)            # ...then computes the CRC that travels with it

def receive(staged, crc):
    return zlib.crc32(staged) == crc             # the storage service checks it on arrival

files = [rng.randbytes(4096) for _ in range(5000)]
accepted_corrupt = rejected = 0
for f in files:
    staged, crc = send(f)
    if not receive(staged, crc):
        rejected += 1
    elif staged != f:
        accepted_corrupt += 1
print(f"{len(files):,} uploads: {rejected} rejected by the check, {accepted_corrupt} stored with a wrong bit and a valid CRC")
Text
5,000 uploads: 0 rejected by the check, 102 stored with a wrong bit and a valid CRC

Career-oriented

Interview prep

Mid level

Q1. What's the difference between error detection and error correction, and when would you use each?

How to get there. Redundancy needed; whether resending is possible.

Q2. Why would you choose CRC-32 over a simple sum of bytes as a checksum?

How to get there. What each misses.

Senior level

Q3. How do you make sure data stored over many years stays correct?

How to get there. End-to-end checks, scrubbing, redundancy.

Q4. A message queue's consumers occasionally receive messages that fail to parse. The producers swear they send valid messages. How do you investigate?

How to get there. Where can damage happen, and where are checks computed?

Staff level

Q5. Your company is designing a new binary file format for customer data that will be read by tools in several languages for years. What do you specify about integrity?

How to get there. Which check, where, how it's described, and what it doesn't cover.

Q6. A team proposes saving bandwidth on an internal replication link by turning off the transport's checksums, arguing that the link is reliable and the application validates records anyway. How do you evaluate it?

How to get there. Expected errors at scale, what the application check covers, the end-to-end argument.