Sub topic 11
Shipping the Code Table with the Compressed Data
A Huffman bitstream cannot be decoded on its own. The bits 0110111 mean nothing unless the decoder knows which code belongs to which symbol, so every compressed file has to carry that information or agree on it in advance. This chapter covers how to do that cheaply and safely.
This chapter assumes you can build Huffman code lengths with a min-heap, assign canonical codes from those lengths, and decode a bitstream bit by bit. It also assumes basic familiarity with Python's struct module and with packing bits into bytes.
What the Decoder Actually Needs
The decoder needs three pieces of information:
- The mapping from codes to symbols.
- Where the payload bits begin.
- Where the payload bits end, because the last byte is usually padded.
The first item is the code table. You can describe it in several ways, and they differ a lot in size and in how fragile they are.
| What you send | Approximate size for n used symbols | Decoder work | Main risk |
|---|---|---|---|
| Symbol frequencies | n symbols plus n counts (often 4 bytes each) | Rerun Huffman exactly | Any difference in tie-breaking produces a different tree |
| Tree shape plus leaf symbols | 2n − 1 shape bits plus 8n symbol bits | Rebuild tree from preorder walk | Custom parser, harder to validate |
| Code lengths (canonical) | One small length per symbol | Run the canonical assignment | Lengths must form a valid prefix code |
| Code lengths, run-length and Huffman coded | Often well under 100 bytes for 286 symbols | Two-stage decode | More complex format |
| Nothing (predefined table) | 0 bytes | Look up a fixed table | Codes fit the data poorly |
Sending frequencies looks natural, but it ties the decoder to the encoder's exact heap behavior. If one side breaks ties differently, both sides get valid Huffman trees, but different ones, and the output turns to garbage. Canonical code lengths avoid this problem. The canonical procedure is deterministic: it sorts by length and then by symbol, so any decoder that receives the lengths rebuilds identical codes. That is why real formats send lengths.
A Complete Container Format
The program below defines a small file format:
- 2 bytes: the number of distinct symbols,
n. npairs of bytes: symbol value and code length.- 4 bytes: the exact number of payload bits.
- The payload, packed most significant bit first and padded with zeros to a whole byte.
import heapq
import struct
from collections import Counter
from itertools import count
def code_lengths(data):
freq = Counter(data)
if not freq:
return {}
if len(freq) == 1:
return {next(iter(freq)): 1}
tiebreak = count()
heap = [(f, next(tiebreak), sym) for sym, f in freq.items()]
heapq.heapify(heap)
while len(heap) > 1:
f1, _, a = heapq.heappop(heap)
f2, _, b = heapq.heappop(heap)
heapq.heappush(heap, (f1 + f2, next(tiebreak), (a, b)))
lengths = {}
def walk(node, depth):
if isinstance(node, tuple):
walk(node[0], depth + 1)
walk(node[1], depth + 1)
else:
lengths[node] = depth
walk(heap[0][2], 0)
return lengths
def canonical_codes(lengths):
ordered = sorted(lengths.items(), key=lambda item: (item[1], item[0]))
codes = {}
code = 0
prev_len = ordered[0][1]
for sym, length in ordered:
code <<= (length - prev_len)
codes[sym] = format(code, "0{}b".format(length))
code += 1
prev_len = length
return codes
def check_lengths(lengths):
# Kraft inequality: sum of 2**-length must not exceed 1.
if any(l < 1 for l in lengths.values()):
raise ValueError("code length must be at least 1")
max_len = max(lengths.values())
total = sum(1 << (max_len - l) for l in lengths.values())
if total > (1 << max_len):
raise ValueError("lengths do not form a prefix code")
def compress(data):
lengths = code_lengths(data)
header = struct.pack(">H", len(lengths))
for sym in sorted(lengths):
header += struct.pack(">BB", sym, lengths[sym])
if not lengths:
return header + struct.pack(">I", 0)
codes = canonical_codes(lengths)
bits = "".join(codes[b] for b in data)
padded = bits + "0" * (-len(bits) % 8)
payload = int(padded, 2).to_bytes(len(padded) // 8, "big")
return header + struct.pack(">I", len(bits)) + payload
def decompress(blob):
(n,) = struct.unpack_from(">H", blob, 0)
pos = 2
lengths = {}
for _ in range(n):
sym, length = struct.unpack_from(">BB", blob, pos)
lengths[sym] = length
pos += 2
(nbits,) = struct.unpack_from(">I", blob, pos)
pos += 4
if n == 0:
return b""
check_lengths(lengths)
reverse = {c: s for s, c in canonical_codes(lengths).items()}
bits = "".join(format(byte, "08b") for byte in blob[pos:])
if len(bits) < nbits:
raise ValueError("payload is truncated")
out, current = bytearray(), ""
for b in bits[:nbits]:
current += b
if current in reverse:
out.append(reverse[current])
current = ""
if current:
raise ValueError("payload ends in the middle of a code")
return bytes(out)
samples = [
b"abracadabra",
b"aaaa",
b"",
bytes(range(256)) * 4,
b"the quick brown fox jumps over the lazy dog" * 50,
]
for sample in samples:
blob = compress(sample)
assert decompress(blob) == sample
print(len(sample), "bytes ->", len(blob), "bytes")The encoder never writes the codes themselves. It writes only lengths, and both sides call the same canonical_codes function. The tree built inside code_lengths is thrown away after the lengths are read off it.
The Header Is Not Free
For b"abracadabra", the code uses 23 payload bits. That rounds up to 3 bytes. The header costs 2 bytes for the count, 10 bytes for five symbol and length pairs, and 4 bytes for the bit count. The result is 19 bytes for an 11-byte input, so the "compressed" file is bigger than the original.
The bytes(range(256)) * 4 sample shows the other extreme. Every byte value appears equally often, so every code is 8 bits long and the payload saves nothing. The 518-byte header is pure loss.
The right header layout depends on how many symbols you expect to use:
- A sparse list of (symbol, length) pairs costs 2 bytes per used symbol. This works well when only a few of the 256 byte values appear.
- A dense array of 256 lengths, with 0 meaning "unused", costs a fixed 256 bytes. If you store each length in 4 bits, it costs 128 bytes. A dense array is cheaper once more than about 64 to 128 symbols are in use.
- You can compress the length array itself. Neighboring symbols often have equal lengths, and long runs of zeros are common, so run-length encoding helps a lot.
DEFLATE uses the last approach. It run-length encodes the literal/length and distance code lengths with special repeat symbols (16, 17, and 18), then Huffman codes that sequence with a third, small code. It sends that small code's 3-bit lengths in a fixed, shuffled order (16, 17, 18, 0, 8, 7, 9, …), so the lengths that are often unused come last and can be cut off.
Marking the End of the Payload
Padding causes a real bug if you skip the bit count. Suppose a has the code 0. The encoder pads the final byte with zero bits, and a naive decoder reads those padding bits as extra a symbols. You can avoid this in two ways:
- Store the exact payload length, in bits or in symbols, as this format does.
- Add an end-of-block symbol to the alphabet and encode it once at the end. DEFLATE does this with symbol 256. It costs one code's worth of bits and makes the stream self-terminating, which suits streaming because the encoder never has to know the total length in advance.
Treat the Header as Untrusted Input
A decoder reads headers that might be corrupt or deliberately malicious. The check_lengths function applies the Kraft inequality: the lengths can form a prefix code only if the sum of 2^(−length) is at most 1. If a header breaks this rule, canonical assignment produces codes that overflow their bit width or turn into prefixes of other codes. Other checks used above:
- Reject a length of 0 for a listed symbol.
- Reject a payload shorter than the declared bit count.
- Reject a stream that ends partway through a code.
A sum below 1 means some bit patterns match no symbol. That is legal here because a single-symbol input gets the code 0 and nothing uses 1. Strict formats such as DEFLATE reject incomplete codes in most cases. The one-symbol case is a special exception.
Header fields also limit code lengths. A 4-bit length field caps codes at 15 bits, which is DEFLATE's limit. Plain Huffman can produce longer codes when frequencies are very skewed, which is why real encoders use length-limited construction.
Skipping the Table Entirely
Sometimes sending no table is the cheapest choice. DEFLATE's block type 1 uses a fixed Huffman code defined in the specification, so short blocks pay no table cost. The JPEG standard publishes example Huffman tables tuned for typical images, and many encoders use them as-is. Motion JPEG streams often leave the tables out of each frame entirely. The trade-off is simple: a predefined table costs zero header bytes but fits any given input worse than a custom one.
Exercise
A file uses 40 distinct byte values. Using this chapter's format, how many header bytes does it need, and would a dense 256-entry array of 4-bit lengths be smaller?
Show answer
The sparse header needs 2 + 40 × 2 + 4 = 86 bytes. A dense array needs 128 bytes for the lengths, plus the same 2-byte field (or none) and the 4-byte bit count, so the sparse format is smaller here. The dense array wins only above roughly 64 used symbols.
Exercise
An encoder sends symbol frequencies instead of lengths. The decoder rebuilds the tree with a heap that breaks ties by symbol value instead of by insertion order. Why can decoding fail even though both trees are valid Huffman trees?
Show answer
When frequencies tie, the order of merges can change, and that produces different tree shapes and different codes for the same symbols. Both trees have the same total encoded length, but they assign different bit patterns, so the decoder reads the wrong symbols. Sending canonical code lengths avoids this because the codes then depend only on the lengths and the symbol order.
Exercise
A corrupted header claims three symbols, each with length 1. What does check_lengths compute, and what would go wrong without the check?
Show answer
With max_len = 1, the total is 1 + 1 + 1 = 3, which is greater than 1 << 1 = 2, so the function raises an error. Without the check, canonical assignment would give the codes 0, 1, and then the counter value 2, which needs two bits and gets formatted as "10". That breaks the 1-bit width, and "1" is a prefix of "10", so the decoder could never output the third symbol.