Sub topic 11
Shipping the Code Table with the Compressed Data
This chapter assumes you can build a Huffman code from frequencies and derive canonical codes from code lengths, as covered in earlier chapters. The question here is practical. The decoder never sees the original text, so how does it learn which code belongs to which symbol?
The decoder needs the same code
A Huffman bitstream is meaningless without its code. The code depends on the input's frequencies, so it changes from file to file. The encoder must write enough information into the file for the decoder to rebuild exactly the same code. That information goes in a header placed before the bitstream.
There are three common choices for what to store:
| What you store | Decoder's work | Typical size | Risk |
|---|---|---|---|
| Symbol frequencies | Re-run Huffman's algorithm | Several bytes per symbol | Tie-breaking must match exactly |
| Tree shape (pre-order bits plus leaf symbols) | Rebuild the tree directly | About 2n bits plus the symbols | Fiddly to parse |
| Code lengths only (canonical) | Assign canonical codes | A few bits per symbol | None, if both sides use the same canonical rule |
Storing frequencies is a common mistake. It is the largest option. It is also fragile: if the decoder's heap breaks ties differently, it builds a different but equally optimal tree and decodes garbage. Code lengths avoid both problems because canonical assignment is deterministic.
A minimal length-based header
The format below writes one byte per possible byte value (0 to 255). A length of 0 means the symbol does not appear.
def canonical_codes(lengths):
ordered = sorted(lengths.items(), key=lambda item: (item[1], item[0]))
codes, code, prev_len = {}, 0, 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 write_header(lengths):
# One byte per possible byte value; 0 means "symbol not used".
return bytes(lengths.get(b, 0) for b in range(256))
def read_header(header):
return {b: n for b, n in enumerate(header) if n > 0}
# Code lengths for "abracadabra"
lengths = {ord("a"): 1, ord("b"): 3, ord("c"): 3, ord("d"): 3, ord("r"): 3}
header = write_header(lengths)
decoder_codes = canonical_codes(read_header(header))
assert decoder_codes == canonical_codes(lengths)
print(len(header), decoder_codes)
# 256 {97: '0', 98: '100', 99: '101', 100: '110', 114: '111'}The encoder and decoder both call the same canonical_codes function. Only the lengths travel in the file.
Where the message ends
Bitstreams rarely fill a whole number of bytes, so the encoder pads the last byte with zeros. Those padding bits could decode as real symbols. For example, a trailing 0 here decodes as an extra a. The file must therefore also record where the message stops, using one of two methods:
- Store the original symbol count in the header, and stop decoding after that many symbols.
- Add a special end-of-block symbol to the alphabet with its own code, and stop when it is decoded. DEFLATE uses this method.
Header overhead matters
A 256-byte header costs nothing on a 1 MB file and ruins a 20-byte one. Real formats shrink the header further:
- Pack each length into 4 bits instead of 8.
- Run-length encode the long runs of zero lengths for unused symbols.
- Huffman-code the code lengths themselves, as DEFLATE does.
- Use predefined tables, such as DEFLATE's fixed codes or JPEG's standard tables, so that no header is needed.
Exercise
"abracadabra" encodes to 23 bits using the lengths above. With the 256-byte header plus a 4-byte symbol count, how large is the compressed file, and how does that compare to the 11-byte original?
Show answer
23 bits pad to 3 bytes, so the file is 256 + 4 + 3 = 263 bytes, about 24 times larger than the 11-byte original. The header dominates. Short inputs need a compact header, a predefined table, or no compression at all.
Exercise
Why is storing code lengths safer than storing frequencies, even though both let the decoder rebuild a valid code?
Show answer
Frequencies require the decoder to re-run Huffman's algorithm, and different tie-breaking can produce a different tree with different codes. Canonical assignment from lengths is deterministic, so any decoder that follows the same rule gets the same codes.