Huffman Coding in Practice
An optimal code is only useful if the decoder knows it and can decode fast. Real formats such as DEFLATE (zip, gzip, PNG) and JPEG solve three practical problems: transmitting the code cheaply (canonical codes), limiting codeword lengths, and adapting to data whose statistics are not known in advance.
Canonical Huffman codes
The decoder only needs the codeword lengths: sorting symbols by (length, symbol) and assigning consecutive binary numbers gives a unique canonical code (The Kraft Inequality). The header then stores one small number per symbol instead of a tree.
import heapq
import numpy as np
def huffman_lengths(p):
heap = [(w, i, [i]) for i, w in enumerate(p)]; heapq.heapify(heap)
lengths = [0] * len(p); counter = len(p)
while len(heap) > 1:
w1, _, s1 = heapq.heappop(heap); w2, _, s2 = heapq.heappop(heap)
for s in s1 + s2: lengths[s] += 1
heapq.heappush(heap, (w1 + w2, counter, s1 + s2)); counter += 1
return lengths
def canonical_code(lengths):
order = sorted(range(len(lengths)), key=lambda i: (lengths[i], i))
code, value, prev = {}, 0, lengths[order[0]]
for i in order:
value <<= lengths[i] - prev; prev = lengths[i]
code[i] = format(value, f"0{lengths[i]}b"); value += 1
return code
text = "this is an example of a huffman tree"
symbols, counts = np.unique(list(text), return_counts=True)
lengths = huffman_lengths(counts / counts.sum())
code = canonical_code(lengths)
encoded = "".join(code[int(np.searchsorted(symbols, ch))] for ch in text)
print("lengths:", dict(zip(symbols.tolist(), lengths)))
print("encoded bits:", len(encoded), " vs 8-bit ASCII:", 8 * len(text))lengths: {' ': 3, 'a': 3, 'e': 3, 'f': 4, 'h': 4, 'i': 4, 'l': 5, 'm': 4, 'n': 4, 'o': 5, 'p': 5, 'r': 5, 's': 4, 't': 4, 'u': 5, 'x': 5}
encoded bits: 135 vs 8-bit ASCII: 288
Decoding fast with tables
Bit-by-bit tree walking is slow. Decoders read bits at once (where is the maximum length) and look up a table of entries holding the symbol and its true length; then they advance by that length. This decodes one symbol per table lookup.
def canonical_code(lengths):
order = sorted(range(len(lengths)), key=lambda i: (lengths[i], i))
code, value, prev = {}, 0, lengths[order[0]]
for i in order:
value <<= lengths[i] - prev; prev = lengths[i]
code[i] = format(value, f"0{lengths[i]}b"); value += 1
return code
lengths = [2, 2, 3, 3, 3, 4, 4]
code = canonical_code(lengths)
k = max(lengths)
table = [None] * (1 << k)
for sym, word in code.items():
pad = k - len(word)
start = int(word, 2) << pad
for j in range(1 << pad):
table[start + j] = (sym, len(word))
message = [0, 5, 2, 1, 6, 3]
bits = "".join(code[s] for s in message) + "0" * k # pad the end
pos, out = 0, []
while len(out) < len(message):
sym, n = table[int(bits[pos:pos + k], 2)]
out.append(sym); pos += n
print("decoded:", out, " table entries:", len(table))decoded: [0, 5, 2, 1, 6, 3] table entries: 16
Length-limited codes
A very rare symbol can get a very long codeword, which makes tables huge. DEFLATE limits lengths to 15 bits and JPEG to 16. A simple fix is to flatten the distribution slightly (for example, give every symbol at least some minimum count) and rebuild; optimal length-limited codes come from the package-merge algorithm. The loss is tiny:
import heapq
import numpy as np
def huffman_lengths(p):
heap = [(w, i, [i]) for i, w in enumerate(p)]; heapq.heapify(heap)
lengths = [0] * len(p); counter = len(p)
while len(heap) > 1:
w1, _, s1 = heapq.heappop(heap); w2, _, s2 = heapq.heappop(heap)
for s in s1 + s2: lengths[s] += 1
heapq.heappush(heap, (w1 + w2, counter, s1 + s2)); counter += 1
return np.array(lengths)
P = 0.5 ** np.arange(1, 21); P = np.append(P, P[-1]); P /= P.sum() # Fibonacci-like, very deep tree
L = huffman_lengths(P)
print("max length:", L.max(), " expected length:", round(float(P @ L), 4))
floor = 1e-4
while True:
Q = np.maximum(P, floor); Q /= Q.sum()
L2 = huffman_lengths(Q)
if L2.max() <= 12:
break
floor *= 2
print("limited to", L2.max(), "bits: expected length", round(float(P @ L2), 4))max length: 20 expected length: 2.0
limited to 12 bits: expected length 2.0034
Static, semi-static and adaptive
| Approach | How the code is chosen | Example |
|---|---|---|
| static | fixed in the standard | JPEG's default tables, fax |
| semi-static | built per block from counts, sent in the header | DEFLATE dynamic blocks |
| adaptive | encoder and decoder update counts after each symbol | adaptive Huffman (Vitter's algorithm) |
Semi-static coding pays a header cost; adaptive coding pays in speed and learns slowly at the start. Arithmetic coding with an adaptive model usually replaces adaptive Huffman today (Arithmetic Coding).
In software
zlib.compress(data, 9)uses dynamic Huffman blocks;zlib.Z_HUFFMAN_ONLYas the strategy turns off the LZ77 part so you can see Huffman alone:
import zlib
import numpy as np
rng = np.random.default_rng(0)
data = rng.choice(np.frombuffer(b"abcdefgh", dtype=np.uint8), size=50_000, p=[0.4, 0.2, 0.1, 0.1, 0.08, 0.06, 0.04, 0.02]).tobytes()
P = np.array([0.4, 0.2, 0.1, 0.1, 0.08, 0.06, 0.04, 0.02])
c = zlib.compressobj(9, zlib.DEFLATED, 15, 9, zlib.Z_HUFFMAN_ONLY)
size = len(c.compress(data) + c.flush())
print(f"Huffman-only DEFLATE: {8 * size / len(data):.3f} bits/symbol, entropy {-np.sum(P * np.log2(P)):.3f}")Huffman-only DEFLATE: 2.593 bits/symbol, entropy 2.491
Exercises
Exercise 1: Header size
A canonical Huffman code for 256 byte values with lengths up to 15 is sent as 4 bits per length. How big is the header?
Answer
128 bytes.
Solution
bits. DEFLATE compresses this header further with another small Huffman code.
Exercise 2: Table size
A decoding table for a code with maximum length 15 has how many entries?
Answer
Solution
. Decoders often use a smaller first-level table (9 or 10 bits) plus secondary tables for the rare long codes.
Exercise 3: Canonical code from a text (code)
Build Huffman lengths and the canonical code for the counts a: 10, b: 6, c: 3, d: 1. Print the codewords.
Answer
a = 0, b = 10, c = 110, d = 111.
Solution
import heapq
def huffman_lengths(p):
heap = [(w, i, [i]) for i, w in enumerate(p)]; heapq.heapify(heap)
lengths = [0] * len(p); counter = len(p)
while len(heap) > 1:
w1, _, s1 = heapq.heappop(heap); w2, _, s2 = heapq.heappop(heap)
for s in s1 + s2: lengths[s] += 1
heapq.heappush(heap, (w1 + w2, counter, s1 + s2)); counter += 1
return lengths
def canonical_code(lengths):
order = sorted(range(len(lengths)), key=lambda i: (lengths[i], i))
code, value, prev = {}, 0, lengths[order[0]]
for i in order:
value <<= lengths[i] - prev; prev = lengths[i]
code[i] = format(value, f"0{lengths[i]}b"); value += 1
return code
code = canonical_code(huffman_lengths([10, 6, 3, 1]))
print({"abcd"[i]: w for i, w in sorted(code.items())}){'a': '0', 'b': '10', 'c': '110', 'd': '111'}
Test yourself
What does a DEFLATE header store to describe a Huffman code?
- only the codeword lengths
- the full tree with pointers
- the symbol probabilities as floats
- nothing: the code is fixed
Why do formats limit Huffman codeword lengths?
- to keep decoding tables small and fast
- because long codes are not prefix-free
- to beat the entropy
- because Kraft's inequality requires it
Table-driven decoding reads k bits at a time where k is…
- the maximum codeword length
- the minimum codeword length
- always 8
- the number of symbols