Sub topic 7
Decoding the Bitstream
This chapter assumes you know Python dictionaries and loops, how binary trees are traversed from root to leaf, and how prefix-free codes work. It also uses the build_codes function from the min-heap chapter.
The working model
A Huffman bitstream has no separators between codes. The decoder can still split it into symbols because the code is prefix-free: no code is the start of another code. Decoding therefore works as a walk through the code tree:
- Start at the root.
- Read one bit. Go left on
0and right on1. - If you reach a leaf, output its symbol and go back to the root.
- Repeat until you have output every expected symbol.
Each bit moves you exactly one step down the tree, so the decoder does constant work per bit. The previous chapter's decoder built up a string and looked it up in a dictionary after every bit. That is easy to read but slower. Production decoders use the tree, or lookup tables derived from it.
Rebuilding the tree from the code table
The decoder usually receives a code table, not the tree. It can rebuild the tree as a trie of nested dictionaries. Each internal node is a dict keyed by "0" and "1", and each leaf is the symbol itself.
import heapq
from collections import Counter
from itertools import count
def build_codes(text):
freq = Counter(text)
tiebreak = count()
heap = [(f, next(tiebreak), sym) for sym, f in freq.items()]
heapq.heapify(heap)
if len(heap) == 1:
_, _, sym = heap[0]
return {sym: "0"}
while len(heap) > 1:
f1, _, left = heapq.heappop(heap)
f2, _, right = heapq.heappop(heap)
heapq.heappush(heap, (f1 + f2, next(tiebreak), (left, right)))
codes = {}
def walk(node, prefix):
if isinstance(node, tuple):
walk(node[0], prefix + "0")
walk(node[1], prefix + "1")
else:
codes[node] = prefix
walk(heap[0][2], "")
return codes
def build_decode_tree(codes):
root = {}
for sym, code in codes.items():
node = root
for bit in code[:-1]:
node = node.setdefault(bit, {})
node[code[-1]] = sym
return root
def decode(bits, codes, n_symbols):
root = build_decode_tree(codes)
out, node = [], root
for b in bits:
node = node[b] # KeyError means an invalid bit path
if not isinstance(node, dict):
out.append(node)
if len(out) == n_symbols:
break
node = root
if len(out) != n_symbols:
raise ValueError("bitstream ended too early or mid-code")
return "".join(out)
text = "abracadabra"
codes = build_codes(text)
bits = "".join(codes[ch] for ch in text)
print(codes) # {'a': '0', 'c': '100', 'd': '101', 'b': '110', 'r': '111'}
print(bits) # 01101110100010101101110 (23 bits)
padded = bits + "0" * (-len(bits) % 8) # pad to a whole byte: 24 bits
print(decode(padded, codes, len(text))) # abracadabraCommon errors
| Mistake | Symptom | Fix |
|---|---|---|
| Ignoring byte padding | Extra symbols at the end. Here the padding bit `0` would decode as an extra `a` | Store the symbol count, or add an end-of-block symbol |
| Encoder and decoder build different tables | Garbage output with no error | Send the table, or send canonical code lengths |
| Stream cut off mid-code | Last symbol silently lost | Check that decoding ended at the root |
| Single-symbol input | The tree has no `1` branch | Treat it as a special case, as `build_codes` does |
Exercise
Using the codes {'a': '0', 'c': '100', 'd': '101', 'b': '110', 'r': '111'}, decode the bitstream 1100111 by walking the tree.
Show answer
110 reaches leaf b, 0 reaches leaf a, and 111 reaches leaf r. The message is "bar".
Exercise
The 23-bit encoding of "abracadabra" is padded with one 0 bit to fill 3 bytes. What does a decoder without a symbol count output, and why?
Show answer
It outputs "abracadabraa". The padding bit 0 is the complete code for 'a', so the decoder emits an extra symbol. A stored length or an end-of-block symbol prevents this.