TExcelTAD
Home › Information Theory › Error Detection and CRCs

Error Detection and CRCs

Often the receiver does not need to fix errors, only to notice them and ask again. Networks resend lost packets, storage systems read from another copy, and files are re-downloaded. Detection needs far fewer redundant bits than correction. The cyclic redundancy check (CRC) is the standard tool: Ethernet, ZIP, PNG and USB all use one.

Parity: the simplest check

A single parity bit makes the number of 1s even. It detects every odd number of flips and misses every even number. On a BSC the probability of an undetected error in a block of nn bits is the probability of a non-zero even number of flips.

python · try it yourself
from scipy.stats import binom

f = 0.01
for n in [8, 64, 1000]:
    undetected = sum(binom.pmf(k, n, f) for k in range(2, n + 1, 2))
    print(f"n = {n:4d}: P(some error) = {1 - (1 - f)**n:.4f}, P(undetected) = {undetected:.4f}")
n =    8: P(some error) = 0.0773, P(undetected) = 0.0026
n =   64: P(some error) = 0.4744, P(undetected) = 0.1116
n = 1000: P(some error) = 1.0000, P(undetected) = 0.5000

For long blocks single parity is weak; also burst errors (several adjacent flips) are common in practice. CRCs handle both.

Polynomial arithmetic over GF(2)

Read a bit string as a polynomial with coefficients 0 or 1: 1101 is x3+x2+1x^3 + x^2 + 1. Addition is XOR and there are no carries. A CRC with generator polynomial g(x)g(x) of degree rr appends rr check bits so that the whole transmitted polynomial is divisible by g(x)g(x).

Encoding: shift the message left by rr bits, divide by g(x)g(x), and use the remainder as the check bits.

python · try it yourself
def crc_remainder(bits, poly):
    r = len(poly) - 1
    work = list(bits) + [0] * r
    for i in range(len(bits)):
        if work[i]:
            for j, p in enumerate(poly):
                work[i + j] ^= p
    return work[-r:]

msg = [1, 1, 0, 1, 0, 1, 1, 0, 1, 1]
g = [1, 0, 0, 1, 1]                      # x^4 + x + 1
check = crc_remainder(msg, g)
codeword = msg + check
print("check bits:", check)
print("receiver recomputes the check bits, they match:", crc_remainder(codeword[:-4], g) == codeword[-4:])
bad = codeword.copy(); bad[3] ^= 1
print("after one flip, check matches:", crc_remainder(bad[:-4], g) == bad[-4:])
check bits: [1, 1, 1, 0]
receiver recomputes the check bits, they match: True
after one flip, check matches: False

What a CRC detects

An error pattern e(x)e(x) goes undetected only if g(x)g(x) divides e(x)e(x). With a well-chosen g(x)g(x) of degree rr:

  • every single-bit error (if gg has at least two terms);
  • every burst of length at most rr;
  • every odd number of errors if x+1x + 1 divides g(x)g(x);
  • a random error pattern with probability about 1−2−r1 - 2^{-r}.
python · try it yourself
import numpy as np

def crc_remainder(bits, poly):
    r = len(poly) - 1
    work = list(bits) + [0] * r
    for i in range(len(bits)):
        if work[i]:
            for j, p in enumerate(poly):
                work[i + j] ^= p
    return work[-r:]

g = [1, 0, 0, 1, 1]                      # degree 4
rng = np.random.default_rng(0)
n_msg, trials = 28, 4000
missed_burst = missed_random = 0
for _ in range(trials):
    msg = rng.integers(0, 2, n_msg).tolist()
    cw = np.array(msg + crc_remainder(msg, g))
    start = rng.integers(0, len(cw) - 4)
    burst = cw.copy(); burst[start] ^= 1; burst[start + 1:start + 4] ^= rng.integers(0, 2, 3)
    rand = cw ^ rng.integers(0, 2, len(cw))
    for word, kind in [(burst, "b"), (rand, "r")]:
        if not np.array_equal(word, cw) and crc_remainder(word[:-4].tolist(), g) == word[-4:].tolist():
            if kind == "b": missed_burst += 1
            else: missed_random += 1
print("missed bursts of length <= 4:", missed_burst)
print(f"missed random errors: {missed_random / trials:.4f}  (about 2^-4 = {2**-4:.4f})")
missed bursts of length <= 4: 0
missed random errors: 0.0648  (about 2^-4 = 0.0625)

CRC-32 in practice

Ethernet, gzip and PNG use CRC-32. Python's zlib.crc32 and binascii.crc32 compute it with table lookups, many bytes per step.

python · try it yourself
import zlib

data = b"The quick brown fox jumps over the lazy dog"
print(f"CRC-32: {zlib.crc32(data):08x}")
corrupted = bytearray(data); corrupted[10] ^= 0x04
print(f"after flipping one bit: {zlib.crc32(bytes(corrupted)):08x}")
CRC-32: 414fa339
after flipping one bit: 9a85e0f5

Detection is not security

A CRC protects against random noise, not against an attacker: anyone can change the data and recompute the CRC. CRCs are also linear, so flipping chosen bits changes the CRC predictably. For integrity against tampering use a cryptographic MAC such as HMAC-SHA-256.

In software

  • zlib.crc32(data, value) can be updated incrementally across chunks by passing the previous value.
  • zlib.adler32 is a faster but weaker checksum used inside zlib streams.
  • Check sums before processing data (ZIP entries, network frames) and request a resend on mismatch: this is automatic repeat request (ARQ).

Exercises

Exercise 1: Parity misses

Which error patterns does a single parity bit miss?

Answer

Every pattern with an even, non-zero number of flips.

Solution

Each flip changes the parity of the number of 1s; an even number of flips restores it.

Exercise 2: Burst detection

A CRC has a generator of degree 16. Which bursts does it always detect?

Answer

Every burst of length at most 16.

Solution

A burst of length b≤rb \le r is xie(x)x^i e(x) with deg⁡e<r\deg e < r and e(0)=1e(0) = 1; g(x)g(x) cannot divide it when gg has a constant term.

Exercise 3: CRC by hand (code)

Compute the CRC check bits of the message 1011 with generator x3+x+1x^3 + x + 1 (bits 1011).

Answer

000: the message itself is the generator, so it is divisible.

Solution
python · try it yourself
def crc_remainder(bits, poly):
    r = len(poly) - 1
    work = list(bits) + [0] * r
    for i in range(len(bits)):
        if work[i]:
            for j, p in enumerate(poly):
                work[i + j] ^= p
    return work[-r:]

print(crc_remainder([1, 0, 1, 1], [1, 0, 1, 1]), crc_remainder([1, 1, 0, 1], [1, 0, 1, 1]))
[0, 0, 0] [0, 0, 1]

The second message 1101 gets check bits 001.

Test yourself

A CRC with a generator of degree r detects every burst error of length…

  1. at most r
  2. at most 2r
  3. exactly r + 1
  4. 1 only

Why is a CRC not enough to protect against tampering?

  1. An attacker can recompute it after changing the data
  2. It is too slow
  3. It only works on text
  4. It cannot detect any errors

What fraction of random error patterns does a CRC with r check bits miss?

  1. about 2−r2^{-r}
  2. about 1r\frac{1}{r}
  3. none
  4. about half