Information TheoryComputer Science, Applied · Book 1
0 / 0

Shelves / Information Theory

IT·05

Codes: Prefix Codes, Kraft's Inequality and Huffman Coding

Variable-length codes that give likely symbols short codewords: why some codes are ambiguous; prefix codes, decoded one bit at a time down a tree; Kraft's inequality, which says exactly which codeword lengths are possible; the proof that no code averages fewer binary digits than the entropy, and that rounding surprises up gets within one; Huffman's algorithm, which finds the best possible code, and its canonical form; where Huffman falls short; and Elias and Rice codes for whole numbers, measured on Shakespeare, dice and sorted ids.

26 topics · ~32 min read · 12-question quiz
Updated Suggest a correction

Start here

What this chapter answers

How can codewords of different lengths be read back without separators? Which sets of codeword lengths can make a code, and which can't? Why can no code beat the entropy, and how close can a code get? How do you find the best code for given probabilities? Why does Huffman's method sometimes still waste a lot, and what do real formats do about it? And how do you code whole numbers whose range you don't know in advance?

Codes in one picture

Chapter 3's source sends A half the time, B a quarter, and C and D an eighth each. A fixed-length code spends 2 binary digits on each. The code A = 0, B = 10, C = 110, D = 111 spends 1, 2, 3 and 3: on average 12·1+14·2+18·3+18·3 =1.75, exactly the entropy. And it can be read without gaps: in 0110100, the first 0 must be A (no other codeword starts with 0), then 110 is C, then 10 is B, then 0 is A. This chapter explains why that works, when it's possible, and how to find such a code for any probabilities.

Variable-length codes

When codes are ambiguous

A code maps each symbol to a codeword, a string of binary digits, and a message is coded by writing its symbols' codewords one after another, with no separators. A code is uniquely decodable if every coded string comes from only one message. Not every code is. With A = 0, B = 01 and C = 10, the string 010 could be A then C, or B then A: the receiver can't tell. The lab finds both readings.

Prefix codes

The simplest way to guarantee unique decoding is to make sure no codeword is the beginning (a prefix) of another.

Interactive diagram: Decoding a prefix code, one digit at a time. It needs JavaScript; the text around it says the same.

A = 0, B = 10, C = 110, D = 111 is a prefix code: 0 starts no other codeword, 10 starts none, and so on. Decoding reads digits one at a time and stops as soon as they form a codeword; there's never a choice. Chapter 2's tree picture makes it obvious: put each codeword at the end of its path from the root (0 for left, 1 for right). A code is a prefix code exactly when every codeword sits at a leaf, never at an internal node on the way to another codeword. Decoding walks from the root down, one digit per step, and emits a symbol at each leaf.

Kraft's inequality

Which codeword lengths are possible? You can't have three codewords of length 1: there are only two strings of length 1. You can have lengths 1, 2, 3, 3, as above, but not 1, 1, 2. Leon Kraft (1949) found the exact rule.

Brockway McMillan (1956) proved that the same inequality holds for every uniquely decodable code, not just prefix codes. So nothing is lost by insisting on prefix codes: any lengths achievable by a uniquely decodable code are achievable by a prefix code, which is also easier to decode. A code whose Kraft sum is exactly 1 is complete: every internal node of its tree has two children, and no binary string is wasted.

How short can a code be?

The entropy bound

Kraft's inequality turns chapter 4's claim into a theorem.

So a code can match the entropy only when every probability is a power of 12 (like 12,14,18,18), and its codeword lengths are then exactly the surprises.

Getting within one bit

Choose each length as the surprise rounded up, li =⌈log21pi⌉. Then 2−li≤pi, so the Kraft sum is at most ∑pi=1 and a prefix code with those lengths exists. Each length is less than its surprise plus 1, so

H≤L¯<H+1.

This is the Shannon code. Together with the bound above, it pins down what's possible: the best code for single symbols averages between H and H+1. The extra fraction of a bit is the price of whole-number lengths, and chapter 6 removes it by coding blocks.

Huffman's algorithm

The Shannon code is within a bit of the entropy, but it isn't always the best: for Shakespeare's letters the lab finds it averaging 4.56 bits against an entropy of 4.19. Huffman's algorithm finds the best.

Interactive diagram: Huffman's algorithm: merge the two lightest. It needs JavaScript; the text around it says the same.

Canonical Huffman codes

A decoder needs the code. Sending the whole tree is wasteful; sending just the lengths is enough if both sides agree on a rule for turning lengths into codewords. The canonical rule sorts symbols by length (and by symbol within a length) and counts upwards in binary, shifting left whenever the length grows: lengths 2, 2, 3, 3, 3 give 00, 01, 100, 101, 110. DEFLATE (the format inside ZIP, gzip and PNG) sends exactly this: one length per symbol, then canonical codes. The lab's coder uses it.

Where Huffman falls short

Huffman is optimal among codes that give each symbol its own whole-number codeword, and that restriction costs.

  • At least one bit per symbol. A symbol of probability 0.99 carries 0.015 bits of surprise but needs a codeword of at least 1 digit. For very predictable sources (a black-and-white image that's mostly white, the "OK" column of chapter 4's exercises) Huffman can be far above the entropy. The fixes are to code blocks of symbols (chapter 6), runs of symbols (run-length coding), or to give up on whole codewords altogether (arithmetic coding, chapter 6).
  • Up to a bit of rounding per symbol. Even without extreme probabilities, Huffman's average is up to 1 bit above H. A die coded one roll at a time costs 2.667 bits against 2.585; coding 3 rolls together costs 2.605 per roll.
  • The probabilities must be known to both ends and sent or agreed in advance. If they change through the file, a fixed code is wrong for part of it. DEFLATE starts a new Huffman table for each block of data; adaptive Huffman coding (Faller 1973, Gallager 1978, Knuth 1985, Vitter 1987) updates the tree as it goes.
  • Very long codewords. Rare symbols can get very long codewords (15 bits for "$" in the plays), which complicate fast decoders, so formats cap the length (15 bits in DEFLATE) with "length-limited" variants of Huffman that cost a tiny amount of compression.

Codes for whole numbers

Sometimes the symbols are whole numbers with no upper limit known in advance: lengths of runs, gaps between sorted ids (chapter 2's exercise C2), counts. A code for them must be a prefix code over infinitely many numbers, giving small numbers short codewords.

  • Unary: n is n−1 ones then a zero. Good if small numbers are very likely (it's the Huffman code for p(n)=2−n), terrible for large ones.
  • Elias gamma (Peter Elias, 1975): write n in binary, and before it as many zeros as it has digits minus one: 1 = 1, 2 = 010, 5 = 00101, 100 = 0000001100100. It costs 2⌊log2n⌋+1 digits, about twice the minimum, for any n, with nothing to tune.
  • Golomb and Rice codes (Solomon Golomb 1966, Robert Rice 1979): choose a parameter k; code n−1 divided by 2k in unary and the remainder in k binary digits. If the numbers are roughly geometric with mean μ, choosing 2k≈0.69μ gives a code within a few percent of the entropy. Lossless audio (FLAC) and image formats use Rice codes for prediction errors.

The lab codes chapter 2's 1,000 sorted ids by their gaps: 20,000 digits as fixed-length ids, 18,298 in Elias gamma, 11,502 in a Rice code with k=9, against an information content of 11,401. Search engines store their posting lists this way.

Lab: codes built and measured

Python
import heapq, itertools
def huffman_lengths(freqs):
    """Codeword length for each symbol of a Huffman code built from {symbol: weight}."""
    if len(freqs) == 1:
        return {s: 1 for s in freqs}
    tie = itertools.count()                       # breaks ties so heapq never compares the dicts
    heap = [(w, next(tie), {s: 0}) for s, w in freqs.items()]
    heapq.heapify(heap)
    while len(heap) > 1:
        w1, _, a = heapq.heappop(heap)            # the two lightest subtrees...
        w2, _, b = heapq.heappop(heap)
        merged = {s: d + 1 for s, d in (a | b).items()}   # ...become children of a new node: one level deeper
        heapq.heappush(heap, (w1 + w2, next(tie), merged))
    return heap[0][2]
def canonical_code(lengths):
    """Assign codewords in order of (length, symbol): the form DEFLATE uses, so only lengths need sending."""
    code, out, prev = 0, {}, 0
    for s, l in sorted(lengths.items(), key=lambda kv: (kv[1], kv[0])):
        code <<= (l - prev)
        out[s] = format(code, f"0{l}b")
        code, prev = code + 1, l
    return out

huffman_lengths keeps a heap of subtrees, each a dictionary from symbol to its depth so far; merging the two lightest adds 1 to every depth in both. canonical_code turns lengths into codewords by counting upwards, as DEFLATE does.

Experiment 1: an ambiguous code and a prefix code

Python
codes = {"A": "0", "B": "01", "C": "10"}                     # not a prefix code: 0 is the start of 01
def parses(bits, codes, sofar=""):
    if not bits:
        return [sofar]
    return [p for s, c in codes.items() if bits.startswith(c) for p in parses(bits[len(c):], codes, sofar + s)]
print("with A=0, B=01, C=10, the bits 010 read as:", parses("010", codes))
prefix = {"A": "0", "B": "10", "C": "11"}
def decode(bits, codes):
    inverse, out, cur = {c: s for s, c in codes.items()}, [], ""
    for b in bits:
        cur += b
        if cur in inverse:                                     # a prefix code: the first match is the only one
            out.append(inverse[cur]); cur = ""
    return "".join(out)
msg = "ABACCAB"
bits = "".join(prefix[c] for c in msg)
print(f"with A=0, B=10, C=11: {msg} -> {bits} -> {decode(bits, prefix)}; parses: {parses(bits, prefix)}")
Text
with A=0, B=01, C=10, the bits 010 read as: ['AC', 'BA']
with A=0, B=10, C=11: ABACCAB -> 01001111010 -> ABACCAB; parses: ['ABACCAB']

With A = 0, B = 01, C = 10, the string 010 has two readings, AC and BA, so the code is useless without separators. The prefix code A = 0, B = 10, C = 11 decodes greedily, digit by digit, and the exhaustive search confirms there's only one reading.

Experiment 2: a Huffman code for Shakespeare's bytes

Python
import math
from collections import Counter
from huff import huffman_lengths, canonical_code
data = open("data/shakespeare.txt", "rb").read()
freq = Counter(data)
n = len(data)
lengths = huffman_lengths(freq)
H = sum(-c / n * math.log2(c / n) for c in freq.values())
L = sum(freq[s] * lengths[s] for s in freq) / n
kraft = sum(2 ** -l for l in lengths.values())
print(f"{len(freq)} symbols; entropy {H:.4f} bits per byte; Huffman average {L:.4f}; Kraft sum {kraft}")
code = canonical_code(lengths)
for s in sorted(freq, key=freq.get, reverse=True)[:3] + sorted(freq, key=freq.get)[:2]:
    print(f"{bytes([s])!r:>7}: p = {freq[s] / n:.5f}, surprise {-math.log2(freq[s] / n):5.2f}, codeword {code[s]} ({lengths[s]} bits)")
print(f"lengths used: {sorted(set(lengths.values()))}; file coded: {L * n / 8:,.0f} bytes of data (plus a table of {len(freq)} lengths)")
Text
65 symbols; entropy 4.7794 bits per byte; Huffman average 4.8170; Kraft sum 1.0
   b' ': p = 0.15232, surprise  2.71, codeword 000 (3 bits)
   b'e': p = 0.08482, surprise  3.56, codeword 0011 (4 bits)
   b't': p = 0.06008, surprise  4.06, codeword 1000 (4 bits)
   b'$': p = 0.00000, surprise 20.09, codeword 111111111111110 (15 bits)
   b'&': p = 0.00000, surprise 18.50, codeword 111111111111111 (15 bits)
lengths used: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; file coded: 671,611 bytes of data (plus a table of 65 lengths)

The Huffman code averages 4.817 binary digits per byte, 0.038 above the order-0 entropy of 4.779, and its Kraft sum is exactly 1 (a complete code, as Huffman codes always are). The space, 15 % of the bytes, gets a 3-digit codeword; "e" and "t" get 4; the rarest symbols, which appear a handful of times, get 15. Coded this way the plays' data would take 671,611 bytes, plus a table of 65 lengths: stage 4 of the capstone predicted 4.781 bits per byte for the order-0 model, and Huffman lands just above it.

Experiment 3: Huffman against the alternatives

Python
import math
from collections import Counter
from itertools import product
from huff import huffman_lengths
for m in (1, 2, 3, 4):
    blocks = {b: (1 / 6) ** m for b in product(range(6), repeat=m)}
    lengths = huffman_lengths(blocks)
    L = sum(blocks[b] * lengths[b] for b in blocks)
    print(f"die rolls coded {m} at a time: {L / m:.4f} binary digits per roll (entropy {math.log2(6):.4f})")
text = open("data/shakespeare.txt", encoding="utf-8").read().lower()
f = Counter(c for c in text if "a" <= c <= "z"); n = sum(f.values())
H = sum(-c / n * math.log2(c / n) for c in f.values())
huff = huffman_lengths(f)
shannon = {s: math.ceil(-math.log2(c / n)) for s, c in f.items()}
for name, lens in (("Huffman", huff), ("Shannon (ceil of surprise)", shannon), ("fixed-length", {s: 5 for s in f})):
    print(f"letters, {name:<27} {sum(f[s] * lens[s] for s in f) / n:.4f} bits per letter (entropy {H:.4f}); Kraft sum {sum(2 ** -l for l in lens.values()):.4f}")
Text
die rolls coded 1 at a time: 2.6667 binary digits per roll (entropy 2.5850)
die rolls coded 2 at a time: 2.6111 binary digits per roll (entropy 2.5850)
die rolls coded 3 at a time: 2.6049 binary digits per roll (entropy 2.5850)
die rolls coded 4 at a time: 2.6049 binary digits per roll (entropy 2.5850)
letters, Huffman                     4.2249 bits per letter (entropy 4.1945); Kraft sum 1.0000
letters, Shannon (ceil of surprise)  4.5631 bits per letter (entropy 4.1945); Kraft sum 0.7920
letters, fixed-length                5.0000 bits per letter (entropy 4.1945); Kraft sum 0.8125

Die rolls coded one at a time cost 2.667 binary digits each, against an entropy of 2.585; coding pairs gives 2.611 and triples 2.605. (Blocks of 4 do no better than blocks of 3, as chapter 2's fixed-length blocks also found: the fit to powers of two isn't steady.) For the letters, Huffman averages 4.225 bits, 0.03 above the entropy; the Shannon code (each surprise rounded up) averages 4.563, and its Kraft sum of 0.79 shows the waste: a fifth of the code space is never used. Fixed-length codes use 5.

Experiment 4: codes for gaps

Python
import math, random
def gamma(n):
    """Elias gamma code of a whole number n >= 1: (length - 1) zeros, then n in binary."""
    b = format(n, "b")
    return "0" * (len(b) - 1) + b
def rice(n, k):
    """Rice code of n >= 1 with parameter k: (n - 1) >> k in unary (ones then a zero), then the low k bits."""
    q, r = (n - 1) >> k, (n - 1) & ((1 << k) - 1)
    return "1" * q + "0" + format(r, f"0{k}b")
for n in (1, 2, 3, 4, 5, 10, 100):
    print(f"gamma({n}) = {gamma(n):<14} rice({n}, k=2) = {rice(n, 2)}")
random.seed(11)
ids = sorted(random.sample(range(1_000_000), 1000))
gaps = [ids[0] + 1] + [b - a for a, b in zip(ids, ids[1:])]
info = (math.lgamma(1_000_001) - math.lgamma(1001) - math.lgamma(999_001)) / math.log(2)
k = max(0, round(math.log2(sum(gaps) / len(gaps) * math.log(2))))
print(f"1,000 ids from a million (mean gap {sum(gaps) / len(gaps):.0f}):")
print(f"  fixed 20-bit ids:        {20 * 1000:>7,} bits")
print(f"  gaps in Elias gamma:     {sum(len(gamma(g)) for g in gaps):>7,} bits")
print(f"  gaps in Rice code, k={k}:  {sum(len(rice(g, k)) for g in gaps):>7,} bits")
print(f"  information, log2 C(n, r): {info:>5,.0f} bits")
Text
gamma(1) = 1              rice(1, k=2) = 000
gamma(2) = 010            rice(2, k=2) = 001
gamma(3) = 011            rice(3, k=2) = 010
gamma(4) = 00100          rice(4, k=2) = 011
gamma(5) = 00101          rice(5, k=2) = 1000
gamma(10) = 0001010        rice(10, k=2) = 11001
gamma(100) = 0000001100100  rice(100, k=2) = 111111111111111111111111011
1,000 ids from a million (mean gap 998):
  fixed 20-bit ids:         20,000 bits
  gaps in Elias gamma:      18,298 bits
  gaps in Rice code, k=9:   11,502 bits
  information, log2 C(n, r): 11,401 bits

Elias gamma needs no parameters but spends about twice the minimum on large numbers: 18,298 bits for 1,000 gaps averaging 998. A Rice code with k=9 (29 =512≈0.69×998) spends 11,502, within 1 % of the 11,401 bits of information in the set. Rice's code for 100 with k=2 shows the danger of a wrong parameter: 27 digits, because the unary part grows with the number.

Worked examples

Checking Kraft

A Huffman code by hand

Elias gamma and Rice

Exercises

Practice

  1. Is {0, 10, 110, 1110} a prefix code? {0, 01, 011}? {00, 01, 10, 11}?
  2. Find the Kraft sum of the lengths 1, 3, 3, 3, 4, 4. Is the code complete?
  3. Build a Huffman code for probabilities 0.5, 0.25, 0.125, 0.125. What's its average length and the entropy?
  4. Build a Huffman code for probabilities 0.3, 0.3, 0.2, 0.1, 0.1 and find its average length.
  5. Write the canonical codewords for lengths 2, 3, 3, 3, 3, 3.
  6. Give the Elias gamma codes of 7, 8 and 16.
  7. A symbol has probability 0.98. What's the shortest codeword it can have in a Huffman code for single symbols, and its surprise?
Answers
  1. Yes; no (0 is a prefix of 01); yes (a fixed-length code is always a prefix code).
  2. 12+38+216 =1: complete.
  3. Lengths 1, 2, 3, 3; average 1.75 = entropy (probabilities are powers of 12).
  4. Merge 0.1 + 0.1 = 0.2; then 0.2 + 0.2 = 0.4; then 0.3 + 0.3 = 0.6; then 0.4 + 0.6. Lengths: 0.3 → 2, 0.3 → 2, 0.2 → 2, 0.1 → 3, 0.1 → 3. Average 0.6+0.6+0.4+0.3+0.3 =2.2.
  5. 00, 010, 011, 100, 101, 110.
  6. 7 = 111, so 00111; 8 = 1000, so 0001000; 16 = 10000, so 000010000.
  7. 1 binary digit; surprise log210.98≈0.029 bits.

Harder

  1. Show that every Huffman code is complete (Kraft sum exactly 1).
  2. Show that a uniquely decodable code that isn't a prefix code exists, by checking that {1, 10, 100} is uniquely decodable. Why can't it be decoded instantaneously?
  3. If all K symbols are equally likely and K is a power of 2, what does Huffman produce? What if K=6?
  4. Show that in an optimal code, a more likely symbol never has a longer codeword than a less likely one.
  5. Explain why sending Huffman lengths with a canonical code is enough for the decoder, and estimate the cost of the table for 256 byte values with lengths up to 15.
Answers
  1. The algorithm always joins two trees into one node with two children, so every internal node of the final tree has exactly two children. In such a tree, Kraft's sum is exactly 1 (each internal node splits its share 2−d evenly between two children, so the shares of the leaves add to the root's share, 1).
  2. Read the string from the right: every codeword ends in 1 followed by zeros (1, 10, 100), so each 1 marks the start of a new codeword, and the zeros after it say which one. So any coded string splits uniquely at the 1s. But reading left to right, after "1" you can't tell whether the codeword is 1, 10 or 100 until you see the next digit (or more): not instantaneous.
  3. All codewords of length log2K: a fixed-length code. For K=6: lengths 2, 2, 3, 3, 3, 3 (four symbols at depth 3, two at depth 2), average 2×2+4×36 =2.667.
  4. Suppose pi>pj but li>lj. Swap the two codewords. The average length changes by pilj+pjli−pili−pjlj =−(pi−pj)(li−lj)<0: it falls, so the original code wasn't optimal. (This exchange argument is the first step of the proof that Huffman's algorithm is optimal.)
  5. With canonical codes, the codeword of every symbol is determined by the list of lengths, so the decoder rebuilds the identical code from them. Lengths from 0 (absent) to 15 fit in 4 bits each, so 256 lengths cost 1,024 bits, 128 bytes; DEFLATE compresses this table further with its own small Huffman code over the lengths.

Challenge

  1. A source has three symbols with probabilities 1−2ε, ε, ε. Find the Huffman code's average length and the entropy as functions of ε, and show that the ratio of average length to entropy grows without bound as ε→0. What does this say about Huffman coding of very predictable sources, and what's the fix?
Discussion

For small ε, Huffman gives lengths 1, 2, 2: average (1−2ε)+4ε =1+2ε, never below 1 bit. The entropy is −(1−2ε)log2(1−2ε)−2εlog2ε, which goes to 0 as ε→0 (it's about 2εlog21ε). So the ratio 1+2εH grows without bound: Huffman can be arbitrarily inefficient relative to the entropy, though never more than 1 bit per symbol above it in absolute terms. For very predictable sources that 1 bit is everything. Fixes: code blocks of symbols (the likely symbol's block of 100 has probability (1−2ε)100, still likely, and gets a short codeword covering many symbols at once), run-length coding (count the runs of the likely symbol), or arithmetic coding, which spends about −log2p per symbol with no whole-number rounding.

In real life

Misconceptions and limits

The model to keep

Common misconceptions

Misconception What's actually true Where it's shown
"Any set of codewords can be decoded if you're careful." {0, 01, 10} is ambiguous: 010 reads as AC or BA. Experiment 1
"Codes must be prefix codes to be decodable." Some non-prefix codes are uniquely decodable, but they can't do better (McMillan). Kraft's inequality; harder exercise 9
"Huffman achieves the entropy." It's within 1 bit; it matches only when probabilities are powers of ½. The entropy bound; Experiment 2
"Rounding each surprise up is optimal." The Shannon code averaged 4.56 bits for letters; Huffman 4.22. Experiment 3
"A very likely symbol can take a fraction of a bit." Not with Huffman: at least 1 bit per symbol. Where Huffman falls short
"The decoder needs the whole code tree." With canonical codes, the lengths are enough. Canonical Huffman codes
"Huffman codes are unique." Tie-breaking gives different trees, all with the same average length. Worked example, five symbols
"Elias gamma is a good default for any numbers." It costs about twice the minimum for large ones; a tuned Rice code was within 1 %. Experiment 4

Limits and trade-offs

  • Huffman is optimal for a restricted problem: one codeword per symbol, known probabilities, no context. Real compressors beat it by changing the problem: better models (context, chapter 7), coding many symbols at once (chapter 6), and adapting.
  • Variable-length codes break random access. With a fixed-length code, symbol i starts at digit iL; with a Huffman code you must decode everything before it. Formats add index points or blocks when random access matters.
  • Errors spread. A single flipped digit in a Huffman-coded stream can make the decoder lose its place and misread everything after it, until it happens to resynchronise. Compressed data needs protection (chapters 8 and 9).

Revision sheet

Key ideas

  • Uniquely decodable: every coded string has one reading. Prefix code: no codeword is a prefix of another; decodable instantly, down a tree.
  • Kraft: lengths li are possible for a prefix code iff ∑2−li≤1; McMillan: the same for any uniquely decodable code. Sum = 1: complete.
  • Entropy bound: average length L¯≥H; equality iff li=log21pi for all i.
  • Shannon code: li =⌈log21pi⌉ gives H≤L¯<H+1.
  • Huffman: merge the two lightest trees until one remains; optimal; always complete.
  • Canonical codes: codewords determined by lengths, counting up; the decoder needs only lengths.
  • Limits: at least 1 bit per symbol; up to 1 bit above H; probabilities must be known.
  • Integer codes: unary; Elias gamma 2⌊log2n⌋+1 digits; Rice with 2k≈0.69× mean.

Glossary

  • Variable-length code: a code whose codewords have different lengths, so likely symbols can get short ones.
  • Uniquely decodable code: a code in which every string of codewords can be split back into symbols in only one way.
  • Prefix code: a code in which no codeword is the beginning of another; it can be decoded symbol by symbol as the digits arrive.
  • Kraft's inequality: the condition ∑2−li≤1 on codeword lengths, necessary and sufficient for a prefix code to exist.
  • Complete code: a prefix code whose Kraft sum is exactly 1, so no binary string is wasted.
  • Average codeword length: ∑pili, the expected number of binary digits per symbol.
  • Shannon code: a code giving each symbol ⌈log21p⌉ digits; within one bit of the entropy.
  • Shannon–Fano coding: building a code by splitting the symbols into two groups of nearly equal probability, recursively; good but not always optimal.
  • Huffman code: the optimal prefix code for given probabilities, built by repeatedly merging the two least likely subtrees.
  • Canonical Huffman code: a Huffman code whose codewords are assigned from the lengths alone by a fixed rule, so only the lengths need sending.
  • Elias gamma code: a prefix code for whole numbers: the binary form preceded by one fewer zeros than it has digits.
  • Rice code: a code for whole numbers: the quotient by 2k in unary, then the remainder in k binary digits.
  • Unary code: writing a whole number n as n−1 ones followed by a zero (or the reverse).