Huffman coding
The conceptWhy Morse code gives the letter E a single dot
Huffman coding gives common symbols short codes and rare ones long codes, so messages shrink. Morse code does this by hand: E, the most common English letter, is one dot. Huffman's 1952 recipe finds the best such code.
Take the 8-letter message AAAABBCD. With a fixed 2 bits per letter it takes 16 bits. Huffman gives A the code 0, B the code 10, C 110 and D 111, so the message takes 14 bits.
What it’s forMeasures how many bits a code spends per symbol on average.
L = Σ pᵢ · ℓᵢ
- pᵢ
- how often symbol i appears, as a fraction (A = 0.5 in AAAABBCD)
- ℓᵢ
- length in bits of symbol i's code (A = 1, D = 3)
- L
- average bits per symbol
What it givesThe average code length, which Huffman makes as small as any code that assigns one codeword per symbol.
- A 0.5×1 + B 0.25×2 = 0.5 + 0.5 = 1
- C 0.125×3 + D 0.125×3 = 0.75
- L = 1.75 bits, versus 2 bits fixed; 8 × 1.75 = 14 bits