TExcelTAD
Home › Information Theory › Symbol Codes and Prefix Codes

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 CC maps each symbol xx to a binary string c(x)c(x) of length ℓ(x)\ell(x). A message x1x2…x_1x_2\dots is encoded as c(x1)c(x2)…c(x_1)c(x_2)\dots. The expected length is

L(C,X)=∑xP(x) ℓ(x)L(C, X) = \sum_x P(x)\,\ell(x)

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?
C1C_1 0 10 11 yes, and prefix-free
C2C_2 0 01 011 yes, but not prefix-free
C3C_3 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.

python · try it yourself
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.

python · try it yourself
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

C2C_2 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

python · try it yourself
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

C1C_1 meets the entropy exactly because every probability is a power of 12\frac{1}{2}.

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 {00,01,10,110,111}\{00, 01, 10, 110, 111\} prefix-free? What is its expected length for P=(0.3,0.3,0.2,0.1,0.1)P = (0.3, 0.3, 0.2, 0.1, 0.1)?

Answer

Yes; 2.2 bits.

Solution

No codeword starts another. L=2(0.3+0.3+0.2)+3(0.1+0.1)=1.6+0.6=2.2L = 2(0.3 + 0.3 + 0.2) + 3(0.1 + 0.1) = 1.6 + 0.6 = 2.2.

Exercise 2: Ambiguity

Is the code a=1a = 1, b=10b = 10, c=101c = 101 uniquely decodable?

Answer

No.

Solution

c(b)c(a)=10⋅1=101=c(c)c(b)c(a) = 10 \cdot 1 = 101 = c(c). 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
python · try it yourself
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…

  1. emit each symbol as soon as its last bit arrives
  2. skip the first bit of each codeword
  3. decode only from the end
  4. use fixed-length codewords only

Which statement is true?

  1. Every prefix code is uniquely decodable
  2. Every uniquely decodable code is prefix-free
  3. Distinct codewords guarantee unique decodability
  4. Prefix codes need lookahead

Prefix codes correspond to…

  1. leaves of a binary tree
  2. rows of a matrix
  3. nodes of a cycle
  4. intervals of equal length