Sub topic 7
Decoding the Bitstream
This chapter assumes you can read Python, know how a binary tree is traversed, and have seen the previous chapter turn a message into a string of bits. Decoding reverses that process. You read a stream of bits with no separators and recover the original symbols one at a time. The prefix-free property is what makes this possible. It also creates edge cases that a careless decoder gets wrong: padding bits, truncated streams, and bit sequences that match no code.
The Running Example
All examples use one fixed prefix-free code for the message abracadabra. It has the same code lengths that a Huffman build can produce for these frequencies (a: 5, b: 2, r: 2, c: 1, d: 1).
| Symbol | Frequency | Code | Bits contributed |
|---|---|---|---|
| a | 5 | 0 | 5 |
| b | 2 | 10 | 4 |
| r | 2 | 110 | 6 |
| c | 1 | 1110 | 4 |
| d | 1 | 1111 | 4 |
The encoded message is 01011001110011110101100, which is 23 bits.
The Working Model: Walk the Tree
The decoder keeps a pointer that starts at the root. For each bit, it moves to the left child on 0 and the right child on 1. When the pointer reaches a leaf, the decoder outputs that leaf's symbol and jumps back to the root. Every symbol sits at a leaf and never at an internal node, so the decoder never has to decide whether a symbol has ended yet. Reaching a leaf is the only signal it needs.
Here are the first few steps on 01011001110...:
| Bits read | Path | Result |
|---|---|---|
| 0 | root → a | output `a`, reset |
| 1, 0 | root → N1 → b | output `b`, reset |
| 1, 1, 0 | root → N1 → N2 → r | output `r`, reset |
| 0 | root → a | output `a`, reset |
| 1, 1, 1, 0 | root → N1 → N2 → N3 → c | output `c`, reset |
The implementation below builds the tree from a code table and validates it along the way. Building the tree is where you catch a table that is not prefix-free. In a real decoder that table comes from a file header and cannot be trusted.
def build_tree(codes):
"""Build a decoding tree from {symbol: bitstring}. Internal nodes are dicts."""
root = {}
for sym, code in codes.items():
if not code:
raise ValueError(f"empty code for {sym!r}")
node = root
for bit in code[:-1]:
child = node.setdefault(bit, {})
if not isinstance(child, dict):
raise ValueError(f"another code is a prefix of the code for {sym!r}")
node = child
if code[-1] in node:
raise ValueError(f"code for {sym!r} collides with or prefixes another code")
node[code[-1]] = sym
return root
def decode_tree(bits, root, count=None):
"""Decode a '0'/'1' string. If count is given, stop after count symbols."""
out = []
node = root
for i, b in enumerate(bits):
node = node.get(b)
if node is None:
raise ValueError(f"bit sequence matches no code (position {i})")
if not isinstance(node, dict): # reached a leaf
out.append(node)
if count is not None and len(out) == count:
return "".join(out) # ignore anything after: padding
node = root
if node is not root:
raise ValueError("bitstream ended in the middle of a code")
if count is not None and len(out) < count:
raise ValueError(f"expected {count} symbols, decoded {len(out)}")
return "".join(out)
codes = {"a": "0", "b": "10", "r": "110", "c": "1110", "d": "1111"}
root = build_tree(codes)
bits = "01011001110011110101100"
print(decode_tree(bits, root)) # abracadabra
print(decode_tree(bits + "0", root, count=11)) # abracadabra (pad bit ignored)Each bit costs one dictionary lookup, so decoding is O(total bits). The tree has exactly n − 1 internal nodes for n symbols, so it stays small.
The Dictionary-Accumulation Approach and Its Gotchas
The decoder from the encoding chapter builds up bits in a string until that string matches a key in a reverse dictionary. Given a valid prefix-free code and a valid stream, it produces the same output as the tree walk. It has two weaknesses.
- Silent failure. If the stream ends partway through a code, the leftover bits in
currentare dropped and no error is raised. The decoder returns a shorter message as though nothing went wrong. - Wasted work per bit. Every bit creates a new string and hashes it. For a code with maximum length L, that is O(L) work per bit instead of O(1).
The tree walk fixes the first problem with its final node is not root check and the second by moving one pointer per bit.
Edge Case: Padding and Knowing Where to Stop
Files and sockets carry whole bytes. The 23-bit message has to be padded to 24 bits, and the decoder cannot tell padding from data. Try padding with a zero:
print(decode_tree("01011001110011110101100" + "0", root)) # abracadabraaIn this code 0 is a complete codeword, so the pad bit decodes as an extra a. Padding with ones only seems safer. One or two 1 bits leave the decoder stranded mid-code, but four of them spell d. No padding pattern is safe for every code, so the format has to tell the decoder where to stop. There are two standard ways to do this.
- Store the symbol count in a header, as
decode_tree(..., count=11)does. The decoder stops after the last symbol and ignores any remaining bits. - Reserve an end-of-block symbol. Add a special symbol to the alphabet, give it a frequency of 1, and encode it once at the end. DEFLATE does this with literal/length symbol 256.
| Strategy | Cost | Works for streaming? | Example |
|---|---|---|---|
| Symbol count in header | A few bytes up front; encoder must know the length in advance | Poorly | Many simple custom formats |
| End-of-block symbol | One rare symbol per block, often 7 to 15 bits | Yes | DEFLATE (symbol 256) |
| Rely on padding | None | No, it decodes wrong | Never use it |
Edge Case: Incomplete Codes and Invalid Bits
A Huffman tree is full: every internal node has two children, so every bit sequence eventually reaches a leaf. A code table read from a damaged or hostile file may not be full. If the decoder follows a bit to a missing child, it must report an error rather than read past the end of an array. This happens in the one-symbol case covered earlier, where the code {"a": "0"} leaves the 1 branch empty:
single = build_tree({"a": "0"})
print(decode_tree("000", single)) # aaa
try:
decode_tree("010", single)
except ValueError as e:
print("error:", e) # error: bit sequence matches no code (position 1)Faster Decoding with a Lookup Table
Production decoders rarely walk the tree one bit at a time. They peek at the next L bits, where L is the maximum code length, and use those bits as an index into a table of 2^L entries. Each entry stores the decoded symbol and its true code length, and the decoder then advances by that length. A code of length k fills 2^(L−k) consecutive entries, because the bits after the code can be anything.
def build_table(codes):
max_len = max(len(c) for c in codes.values())
table = [None] * (1 << max_len)
for sym, code in codes.items():
shift = max_len - len(code)
start = int(code, 2) << shift
for j in range(start, start + (1 << shift)):
table[j] = (sym, len(code))
return table, max_len
def decode_table(bits, codes, count):
table, max_len = build_table(codes)
out, pos = [], 0
while len(out) < count:
window = bits[pos:pos + max_len].ljust(max_len, "0") # pad the final peek
entry = table[int(window, 2)]
if entry is None:
raise ValueError(f"bit sequence matches no code (position {pos})")
sym, length = entry
if pos + length > len(bits):
raise ValueError("bitstream ended in the middle of a code")
out.append(sym)
pos += length
return "".join(out)
codes = {"a": "0", "b": "10", "r": "110", "c": "1110", "d": "1111"}
print(decode_table("01011001110011110101100", codes, 11)) # abracadabraThe decoder pads the final peek with zeros so the window always has L bits. The pos + length check then rejects any match that used those invented bits.
Trade-offs Between the Two Decoders
| Property | Tree walk | Single-level table |
|---|---|---|
| Work per symbol | One step per bit (up to L) | One lookup |
| Memory | n − 1 internal nodes | 2^L entries |
| L = 15 (DEFLATE's limit) | Trivial | 32,768 entries, which hurts cache performance |
| Handles any code length | Yes | Only if 2^L fits in memory |
Real decoders such as zlib split the difference with a two-level table. A primary table covers about 9 or 10 bits, which handles the common short codes in one lookup. Rare long codes point to small secondary tables. This is also one reason formats cap code lengths, which a later chapter on length-limited codes covers.
Exercises
Exercise
Using the code a=0, b=10, r=110, c=1110, d=1111, decode the bitstream 1101110010 by hand. Show where each symbol boundary falls.
Show answer
110 | 1110 | 0 | 10 decodes to "rcab". Each boundary falls where the tree walk reaches a leaf. After 1, 1, 0 the walk reaches r. After 1, 1, 1, 0 it reaches c. Then 0 gives a, and 1, 0 gives b.
Exercise
An encoder writes the 23-bit abracadabra stream and pads it to 24 bits with a single 1. The decoder uses the spine's dictionary-accumulation decoder with no symbol count. What does it return, and why is that dangerous?
Show answer
It returns "abracadabra". The pad bit 1 is a proper prefix of b, r, c and d, so it sits unmatched in current and is silently dropped. Here the output happens to be correct, but the same decoder would also silently drop the last few bits of a truncated stream. It never reports that the stream ended mid-code, so it cannot tell padding from data loss. Pad with 0 instead and it returns "abracadabraa". The fix is to store a symbol count or encode an end-of-block symbol.
Exercise
A code has a maximum length of 15 bits, and its shortest code is 2 bits long. In a single-level lookup table, how many entries does one 2-bit code fill, and how large is the whole table? Why do production decoders use two-level tables instead?
Show answer
The table has 2^15 = 32,768 entries. A 2-bit code fills 2^(15−2) = 8,192 of them. The full table is too large to stay in a fast CPU cache and slow to rebuild for every block, even though most lookups hit short codes. A two-level table uses a primary table of about 2^9 entries for the short, common codes and small secondary tables for the rare long ones. It keeps one-lookup decoding for most symbols and uses far less memory.