Symbol Codes and Prefix Codes
The source coding theorem uses huge blocks and allows failure. In practice we usually want a symbol code: each symbol gets its own binary codeword, the codewords are concatenated, and decoding never fails. The question is which sets of codewords can be decoded without ambiguity, and how short they can be.
Symbol codes
A symbol code maps each symbol to a binary string of length . A message is encoded as . The expected length is
Uniquely decodable codes
A code is uniquely decodable if no two different messages have the same encoding. This is stronger than just having distinct codewords:
| Code | a | b | c | Uniquely decodable? |
|---|---|---|---|---|
| 0 | 10 | 11 | yes, and prefix-free | |
| 0 | 01 | 011 | yes, but not prefix-free | |
| 0 | 1 | 01 | no: 01 is c or ab |
Prefix codes
A code is prefix-free (a prefix code) if no codeword is a prefix of another. Then the decoder can read bits one by one and emit a symbol the moment the bits match a codeword, with no lookahead. Prefix codes correspond to binary trees whose leaves are the codewords.
def is_prefix_free(code):
words = sorted(code.values())
return all(not words[i + 1].startswith(words[i]) for i in range(len(words) - 1))
def decode_prefix(bits, code):
inverse = {w: s for s, w in code.items()}
out, cur = [], ""
for b in bits:
cur += b
if cur in inverse:
out.append(inverse[cur]); cur = ""
return "".join(out), cur == ""
C1 = {"a": "0", "b": "10", "c": "11"}
C2 = {"a": "0", "b": "01", "c": "011"}
msg = "abcab"
bits = "".join(C1[s] for s in msg)
print("C1 prefix-free:", is_prefix_free(C1), " C2 prefix-free:", is_prefix_free(C2))
print("encoded:", bits, " decoded:", decode_prefix(bits, C1))C1 prefix-free: True C2 prefix-free: False
encoded: 01011010 decoded: ('abcab', True)
Sorting the codewords works because if any codeword is a prefix of another, it is also a prefix of its immediate successor in sorted order.
Testing unique decodability
For codes that are not prefix-free, the Sardinas-Patterson test decides unique decodability. It repeatedly computes "dangling suffixes" left over when one codeword is a prefix of another (or of a suffix); the code is uniquely decodable unless some dangling suffix is itself a codeword.
def uniquely_decodable(words):
words = set(words)
def dangling(A, B):
return {b[len(a):] for a in A for b in B if b.startswith(a) and b != a}
S = dangling(words, words)
seen = set()
while S:
if S & words:
return False
key = frozenset(S)
if key in seen:
return True
seen.add(key)
S = dangling(words, S) | dangling(S, words)
return True
for name, code in [("C1", ["0", "10", "11"]), ("C2", ["0", "01", "011"]), ("C3", ["0", "1", "01"]),
("C4", ["1", "011", "01110", "1110", "10011"])]:
print(name, code, "uniquely decodable:", uniquely_decodable(code))C1 ['0', '10', '11'] uniquely decodable: True
C2 ['0', '01', '011'] uniquely decodable: True
C3 ['0', '1', '01'] uniquely decodable: False
C4 ['1', '011', '01110', '1110', '10011'] uniquely decodable: False
is uniquely decodable but the decoder must look ahead: after 0 it cannot know whether a ended until it sees the next bits. Prefix codes avoid this, and as the next lesson shows, they cost nothing in code length (The Kraft Inequality).
Expected length
import numpy as np
P = {"a": 0.5, "b": 0.25, "c": 0.25}
for name, code in [("C1", {"a": "0", "b": "10", "c": "11"}), ("fixed", {"a": "00", "b": "01", "c": "10"})]:
L = sum(P[s] * len(w) for s, w in code.items())
print(f"{name:5s}: expected length {L} bits/symbol")
print("entropy:", -sum(p * np.log2(p) for p in P.values()))C1 : expected length 1.5 bits/symbol
fixed: expected length 2.0 bits/symbol
entropy: 1.5
meets the entropy exactly because every probability is a power of .
In software
- DEFLATE (zip, gzip, PNG) uses prefix codes for literals and match lengths, transmitted as code lengths only (canonical Huffman codes, see Huffman Coding in Practice).
- UTF-8 is a prefix code over bytes: the leading bits of the first byte tell the decoder how many bytes the character has.
Exercises
Exercise 1: Prefix-free?
Is prefix-free? What is its expected length for ?
Answer
Yes; 2.2 bits.
Solution
No codeword starts another. .
Exercise 2: Ambiguity
Is the code , , uniquely decodable?
Answer
No.
Solution
. Two different messages, ba and c, give the same bits.
Exercise 3: Decode a stream (code)
Decode 110100111010 with the prefix code a = 0, b = 10, c = 110, d = 111.
Answer
cbadab.
Solution
code = {"a": "0", "b": "10", "c": "110", "d": "111"}
inverse = {w: s for s, w in code.items()}
out, cur = "", ""
for bit in "110100111010":
cur += bit
if cur in inverse:
out += inverse[cur]; cur = ""
print(out)cbadab
Test yourself
A prefix code lets the decoder…
- emit each symbol as soon as its last bit arrives
- skip the first bit of each codeword
- decode only from the end
- use fixed-length codewords only
Which statement is true?
- Every prefix code is uniquely decodable
- Every uniquely decodable code is prefix-free
- Distinct codewords guarantee unique decodability
- Prefix codes need lookahead
Prefix codes correspond to…
- leaves of a binary tree
- rows of a matrix
- nodes of a cycle
- intervals of equal length