Sub topic 6
Encoding a Message
This chapter assumes you have already built a Huffman code table: a dictionary that maps each symbol to a bit string, made with the min-heap algorithm from the previous chapter. You should be comfortable with Python dictionaries, string joining, and bitwise operators (<<, |, &). It also assumes you know what a byte is and how binary numbers map to integers.
Encoding is the simplest stage of Huffman coding, but it still has sharp edges. Bits must be packed into bytes. Padding at the end of the last byte can confuse the decoder. Symbols that are missing from the table cause errors. The bit order inside a byte must match what the decoder expects. This chapter covers each of these.
The working model: look up, then concatenate
A Huffman encoder handles one symbol at a time. For each symbol in the input, it looks up that symbol's code and appends the code's bits to the output. It inserts no separators, because the code is prefix-free: no codeword is the start of another, so the decoder can always tell where one ends.
The code below repeats the tree builder so that the example runs on its own, then encodes a message as a string of "0" and "1" characters.
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)
text = "abracadabra"
codes = build_codes(text)
bits = encode(text, codes)
print(codes)
print(bits, len(bits), "bits vs", 8 * len(text))The output is:
{'a': '0', 'c': '100', 'd': '101', 'b': '110', 'r': '111'}
01101110100010101101110 23 bits vs 88Tracing the encoding by hand
The table shows each symbol of abracadabra with the bits it adds.
| Position | Symbol | Code | Bits so far |
|---|---|---|---|
| 1 | a | 0 | 0 |
| 2 | b | 110 | 0110 |
| 3 | r | 111 | 0110111 |
| 4 | a | 0 | 01101110 |
| 5 | c | 100 | 01101110100 |
| 6 | a | 0 | 011011101000 |
| 7 | d | 101 | 011011101000101 |
| 8 | a | 0 | 0110111010001010 |
| 9 | b | 110 | 0110111010001010110 |
| 10 | r | 111 | 0110111010001010110111 |
| 11 | a | 0 | 01101110100010101101110 |
Predicting the output size
You can know the encoded length before you encode anything. It equals the sum, over all symbols, of frequency times code length:
| Symbol | Frequency | Code length | Bits contributed |
|---|---|---|---|
| a | 5 | 1 | 5 |
| b | 2 | 3 | 6 |
| r | 2 | 3 | 6 |
| c | 1 | 3 | 3 |
| d | 1 | 3 | 3 |
| Total | 11 | 23 |
This is useful in practice. Compressors such as DEFLATE use it to decide whether a block should use a custom Huffman table, a fixed table, or no compression at all, without encoding the block three times.
def predicted_bits(text, codes):
return sum(f * len(codes[sym]) for sym, f in Counter(text).items())
print(predicted_bits(text, codes)) # 23The 23 bits cover only the payload. A real file must also carry the code table, which a later chapter covers. For an 11-character message the table costs more than the 65 bits saved. Huffman coding pays off on longer inputs.
From bit strings to real bytes
A string of "0" and "1" characters is good for teaching, but each character uses a full byte of memory, so this "compressed" output is eight times larger than the original. Files store bytes, so the bits have to be packed eight to a byte.
def pack_bits(bits):
pad = (-len(bits)) % 8
padded = bits + "0" * pad
data = bytes(int(padded[i:i + 8], 2) for i in range(0, len(padded), 8))
return data, pad
data, pad = pack_bits(bits)
print(data.hex(), "padding bits:", pad) # 6e8adc padding bits: 1The 23 bits fill two whole bytes (01101110 = 0x6E, 10001010 = 0x8A) and leave 7 bits over. One zero bit pads them out to 11011100 = 0xDC.
A direct encoder with an integer bit buffer
Production encoders never build the intermediate string. They store each code as an integer value plus a bit length, shift the code into an accumulator, and write out whole bytes as soon as they are ready.
def encode_to_bytes(text, codes):
table = {sym: (int(c, 2), len(c)) for sym, c in codes.items()}
out = bytearray()
acc = 0 # pending bits, right-aligned
nbits = 0 # how many pending bits are valid
total = 0
for ch in text:
value, length = table[ch]
acc = (acc << length) | value
nbits += length
total += length
while nbits >= 8:
nbits -= 8
out.append((acc >> nbits) & 0xFF)
acc &= (1 << nbits) - 1 # drop bits already written
if nbits:
out.append((acc << (8 - nbits)) & 0xFF)
return bytes(out), total
packed, total_bits = encode_to_bytes(text, codes)
print(packed.hex(), total_bits) # 6e8adc 23
assert packed == dataThe mask line keeps the accumulator small. Without it, acc would grow into a huge Python integer holding every bit of the message, and each shift would cost time proportional to the message length.
Common errors
Padding that decodes as data
The padding bit in the example is 0, and 0 is also the code for a. A decoder that reads every bit in the file will output abracadabraa, with an extra a on the end. This bug turns up whenever the shortest code is made only of padding-value bits, which is often.
There are three standard fixes:
- Store the number of valid bits (or of symbols) in a header, so the decoder stops in time.
- Add an end-of-stream symbol with its own frequency of 1, so it gets a code like any other symbol, and encode it last. DEFLATE does this with symbol 256, the end-of-block code.
- Store the padding count in a few header bits, as
pack_bitsmakes possible.
Symbols missing from the table
codes[ch] raises KeyError for a symbol that was not in the text used to build the table. This cannot happen when you build the table from the same input you encode. It does happen when a table is trained on sample data and then reused. To handle this, either give every possible symbol a small nonzero count before building the tree, or reserve an escape code that is followed by the raw symbol.
The single-symbol input
For input like "aaaa", the tree has one leaf and no edges, so the walk would assign it the empty code "". Encoding would then produce zero bits, and the message length would be lost. This is why build_codes assigns "0" in this case. The output becomes "0000", one bit per symbol, and the decoder still needs the symbol count.
Quadratic string building
Writing bits += codes[ch] inside a loop can take quadratic time, because Python strings are immutable. CPython sometimes optimizes this pattern, but you should not depend on it. Use "".join(...), a bytearray, or the integer buffer shown above.
Bit order inside a byte
The packers in this chapter are MSB-first: the first code bit goes into the most significant bit (bit 7) of the byte. JPEG works this way. DEFLATE fills each byte starting from the least significant bit and stores Huffman codes with their bits reversed, so that the decoder can read them correctly in that order. Neither choice is better than the other, but the encoder and decoder must agree. A mismatch produces garbage on the first symbol that has a code longer than one bit. The DEFLATE and JPEG chapter covers this in detail.
| Concern | MSB-first (this chapter, JPEG) | LSB-first (DEFLATE) |
|---|---|---|
| First code bit placed in | bit 7 of the byte | bit 0 of the byte |
| Codes written | as-is | bit-reversed |
| Reads naturally as | a printed bit string | integer shifts to the right |
Exercises
Exercise
Using the code table {'a': '0', 'c': '100', 'd': '101', 'b': '110', 'r': '111'}, encode "cab" as a bit string, give its length, and give the packed byte in hex using MSB-first packing with zero padding.
Show answer
c=100, a=0, b=110, so the bits are 1000110 (7 bits). Padding with one 0 gives 10001100 = 0x8C.
Exercise
A message has frequencies x:10, y:6, z:3, w:1 and the code lengths 1, 2, 3, 3. How many payload bits does the encoded message need, and how many bytes after packing?
Show answer
101 + 62 + 33 + 13 = 34 bits. Packed, that is 5 bytes (40 bits), with 6 padding bits.
Exercise
Why does decoding the packed "abracadabra" bytes without a length header give one extra character, and which character is it?
Show answer
The 23 bits are padded with a single 0 to fill 24 bits. The code for 'a' is '0', so a decoder that reads every bit outputs an extra 'a' at the end.
Exercise
In encodetobytes, what goes wrong if you delete the line acc &= (1 << nbits) - 1?
Show answer
The output stays correct, because each byte is pulled out with a shift and & 0xFF. But acc keeps every bit of the message, so it grows without limit and each shift gets slower as the message gets longer. Encoding becomes quadratic in time and linear in extra memory.