Sub topic 6
Encoding a Message
This chapter assumes you can read Python, know what a bit and a byte are, and have seen the build_codes function from the previous chapter. That function turns a text into a table that maps each symbol to a Huffman code. Encoding means using that table to turn a message into a bitstream.
The Working Model
Encoding is a lookup and a concatenation. For each symbol in the message, find its code in the table and append it to the output. Because the code is prefix-free, you need no separators between codes. The decoder can always tell where one code ends and the next begins.
For "abracadabra" the frequencies are a=5, b=2, r=2, c=1, d=1. The tree-building step produces this table:
| Symbol | Count | Code | Bits contributed |
|---|---|---|---|
| a | 5 | 0 | 5 |
| b | 2 | 110 | 6 |
| r | 2 | 111 | 6 |
| c | 1 | 100 | 3 |
| d | 1 | 101 | 3 |
The total is 23 bits. Stored as 8-bit ASCII, the same 11 characters take 88 bits.
Encoding in Code
The program below builds the codes, encodes the message, and then packs the bit string into real bytes.
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 encode(text, codes):
return "".join(codes[ch] for ch in text)
def pack_bits(bits):
pad = (8 - len(bits) % 8) % 8
padded = bits + "0" * pad
data = bytes(int(padded[i:i + 8], 2) for i in range(0, len(padded), 8))
return data, len(bits)
text = "abracadabra"
codes = build_codes(text)
bits = encode(text, codes)
data, bit_count = pack_bits(bits)
print(codes)
print(bits, len(bits), "bits vs", 8 * len(text))
print(data.hex(), bit_count)The output is:
{'a': '0', 'c': '100', 'd': '101', 'b': '110', 'r': '111'}
01101110100010101101110 23 bits vs 88
6e8adc 23Packing Bits into Bytes
Files and sockets work in whole bytes, so the 23 bits need one padding bit to fill 3 bytes. The padding causes a real problem. The decoder can't tell padding bits from code bits. A trailing 0 here would decode as an extra a. That is why pack_bits returns the true bit count, which must be stored with the data. The other common fix is an end-of-stream symbol that gets its own code. DEFLATE takes this approach with its end-of-block symbol.
Common Errors
- Missing symbols.
codes[ch]raisesKeyErrorif the message has a symbol that wasn't in the text used to build the table. Build the table from the data you encode, or from a fixed alphabet that covers every possible symbol. - Mismatched tables. The decoder must use the exact same code table. Rebuilding the tree with different tie-breaking can assign different codes to symbols with equal counts. The chapter on canonical codes fixes this.
- Slow concatenation. Appending to a string in a loop can be slow on large inputs.
"".join(...)or a bit buffer that writes whole bytes scales better.
Exercise
Using the table above, encode "abba". How many bits does it take, how many bytes after packing, and what is the hex value?
Show answer
a=0, b=110, b=110, a=0 gives "01101100", which is 8 bits. That fills exactly 1 byte with no padding, and the hex value is 6c.
Exercise
The bit string for "abracadabra" is padded with one 0 bit. If the bit count were not stored, what would a decoder output?
Show answer
The decoder would read the padding 0 as the code for a and output "abracadabraa", which has one extra a at the end.