Coding and Entropy §
Coding and entropy study how to represent data using the fewest bits. They are relevant whenever storage or bandwidth is limited and the data’s statistical structure can be exploited.
Authoritative sources
Fixed-length vs. variable-length codes §
A fixed-length code assigns every symbol the same number of bits: bits per symbol, regardless of probability. ASCII is the canonical example: 7 bits for every character, whether it is a common e or a rare z.
A variable-length (prefix-free) code assigns shorter codewords to more probable symbols and longer ones to rarer symbols. The constraint is that no codeword may be a prefix of another, so the decoder can always tell where one symbol ends and the next begins. The expected length of such a code can be strictly less than whenever the distribution is non-uniform.
This distinction motivates the rest of the page: entropy quantifies how much shorter a variable-length code can be, and the source coding theorem and Huffman coding show how close to that limit one can get.
Details
Step 1 — what decoding requires. The decoder receives one long bit string with no separators and must split it into codewords, left to right. The split must be unique for every possible string, otherwise the message is ambiguous.
Step 2 — what goes wrong without prefix-freeness. Take the code A = 0, B = 1, C = 01. The bit string 01 has two valid readings:
- a single symbol C,
- the symbol A followed by the symbol B.
The decoder cannot tell which one was sent. The problem is that 0 (a codeword for A) is a prefix of 01 (a codeword for C): after reading 0, the decoder cannot know whether the codeword is already complete.
Step 3 — why prefix-freeness fixes it. If no codeword is a prefix of another, the decoder can read bits left to right and stop at the first codeword that matches. That first match is the only possible one, because no longer codeword can start with those same bits. Decoding is then a simple greedy scan — no separators, no length fields, no backtracking.
Step 4 — the tree picture. A binary code is a binary tree: each edge is a bit (left = 0, right = 1), and each codeword is the path from the root to a node. Prefix-freeness means exactly that all symbols sit on leaves: a codeword that is a prefix of another would be an internal node with children, which is impossible if every symbol is a leaf.
Here A = 0, B = 10, C = 110, D = 111. Every symbol is a leaf, so the code is prefix-free and the greedy scan decodes any bit string uniquely.
Example problem
Using the code above (A = 0, B = 10, C = 110, D = 111):
- Decode the bit string
100110111. - Is the code {A =
0, C =01} prefix-free? Why not, and what does it break?
Solution
- Scan left to right, stopping at the first codeword match:
10→ B, then0→ A, then110→ C, then111→ D. The string decodes to B A C D. The first-match rule is unambiguous precisely because the code is prefix-free. - No:
0is a prefix of01. The string01could be a single C or an A followed by a1-starting codeword — the greedy first-match scan would misdecode it. This is exactly the ambiguity of Step 2.
Information and entropy §
The self-information of an event with probability is bits.
The entropy of a discrete random variable with distribution is:
Entropy is the average self-information and the lower bound on the expected code length of any lossless prefix-free code.
Details
Properties:
- iff is deterministic.
- , with equality iff is uniform.
- (chain rule).
- (subadditivity).
Mutual information: . It measures how much knowing reduces uncertainty about .
Conditional entropy: . The number of bits still needed to describe after observing .
All logarithms in this page are base 2, so all quantities are in bits.
Example: English text has entropy – bits/character over a 27-character alphabet (26 letters + space), versus bits for a uniform distribution. The achievable compression ratio is therefore to of the original size. Shannon’s 1951 estimate in Prediction and Entropy of Printed English gives the 0.6–1.3 range.
Redundancy §
The redundancy of a source is the fraction of the available code space wasted by the source’s non-uniform distribution:
A uniform source has (no waste); a highly skewed source has close to 1 (most of the code space is unused).
Details
For English text (27-character alphabet, bits/char as a midpoint): . This means roughly 79% of the 4.75 bits per character are “wasted” because the distribution is far from uniform. Redundancy is what lossless compression exploits: by using a variable-length code, the compressor removes this waste and approaches the entropy bound.
Redundancy is also the quantity that error-correcting codes introduce deliberately (see Communication): a small amount of added redundancy makes the code robust to channel noise.
Kraft inequality §
A set of codeword lengths is realizable as a binary prefix-free code if and only if:
This is the Kraft inequality. It is the key combinatorial constraint that makes the coding problem well-posed: it says the codewords must “fit” in the binary tree without overlapping.
Details
Intuition: each codeword of length occupies a subtree of size of the full binary tree. The Kraft inequality says these subtrees must be disjoint (total area ). Equality holds when the tree is full (every internal node has two children).
The picture below shows the code space as a unit square: each codeword of length claims a rectangle of area . For the prefix-free code A = 0, B = 10, C = 110, D = 111, the four rectangles exactly tile the square (Kraft sum = 1, a full tree). A code whose rectangles did not fill the square would leave unused code space; rectangles that overlapped would correspond to a prefix violation, which is impossible.
Necessity: in any prefix-free code, the leaves are disjoint subtrees, so their total area is at most 1.
Sufficiency: if the inequality holds, one can construct a prefix-free code with exactly those lengths by filling a binary tree level by level (a greedy leaf-placement algorithm).
The Kraft inequality is the constraint under which Huffman coding optimizes the expected length, and it is the tool used in the proof of the source coding theorem.
Source coding theorem §
Theorem (Shannon’s first theorem). For any discrete memoryless source with entropy , and any prefix-free code with expected codeword length :
The lower bound is tight: there exists a prefix-free code whose expected length is within 1 bit of the entropy. For block codes of length (encoding -tuples of symbols), the gap shrinks to per symbol, so the bound is asymptotically tight.
Details
Lower bound ():
Let be the codeword length for symbol with probability . By the Kraft inequality, . Define ; then . Extend to a proper distribution by adding a dummy symbol with probability .
By the Gibbs inequality (relative entropy is non-negative):
Since , the right side is . The left side is . Hence .
Upper bound ():
Choose codeword lengths . Then , so:
It remains to verify the Kraft inequality. Since by definition, the first sum is exactly:
where the single inequality uses , hence . So the lengths are realizable, and a prefix-free code with expected length exists.
Typical-set intuition: the theorem has a purely combinatorial reading. For a sequence of i.i.d. symbols, the law of large numbers concentrates almost all probability mass on the typical set: roughly sequences, each with probability close to . Indexing one typical sequence therefore takes about bits, i.e. bits per symbol. The atypical sequences outside this set are exponentially rare, so giving them long codewords costs almost nothing in expectation. This counting argument is the heart of the theorem, and it explains why encoding blocks of symbols shrinks the gap to per symbol.
Huffman coding §
Huffman coding is a greedy algorithm that constructs the optimal prefix-free code (minimum expected length) for a known probability distribution.
Algorithm:
- Start with a leaf node for each symbol, weighted by its probability.
- Repeatedly merge the two least-probable nodes into a new parent node whose probability is the sum.
- Assign bit 0 to one child and bit 1 to the other at each merge.
- The codeword for each symbol is the path from the root to its leaf.
Optimality theorem: The Huffman code is the prefix-free code with the minimum expected codeword length for the given distribution. It satisfies , and the gap is strictly less than 1 bit per symbol.
The Kraft inequality is the constraint that makes the problem well-posed: among all length assignments satisfying Kraft, Huffman finds the one that minimizes .
Details
Why greedy works: the two least-probable symbols are always siblings at the deepest level of the optimal tree (exchange argument). Merging them reduces the problem to symbols, and the greedy choice is locally optimal at every step.
Example: probabilities (the distribution animated in the diagram above).
- Merge 0.125 + 0.125 → 0.25
- Merge 0.25 + 0.25 → 0.5
- Merge 0.5 + 0.5 → 1.0
- Codewords:
0,10,110,111. Expected length = 1.75 = (exact, because all probabilities are powers of 2, so every is an integer and no codeword needs rounding up).
Shannon–Fano coding: the other classical way to build a prefix-free code. It works top-down: sort the symbols by decreasing probability, recursively split the ordered list into two groups of approximately equal total probability, and assign bit 0 to one group and bit 1 to the other. This contrasts with Huffman’s bottom-up greedy merge. Shannon–Fano is simple and often close to optimal, but its split can waste code space, so it does not always reach the Huffman optimum; Huffman’s construction is the one with the optimality guarantee above.
Practical use: Huffman coding is the entropy-coding stage in DEFLATE (gzip, PNG, ZIP), JPEG, and MP3. See Compression for how it is combined with other techniques.
Huffman coding is not the only way to approach the entropy bound. Arithmetic coding encodes the entire message as a single interval in and achieves the entropy bound more closely: the total overhead is less than 2 bits for the whole message, not per symbol. See Compression for details.
Encodings §
Practical character and data encodings come in two families, constrained by two different things:
- A variable-length, prefix-free code such as UTF-8 is constrained by the source distribution: it assigns shorter codewords to more probable symbols, exactly like Huffman coding.
- A fixed-length code such as Base-32 or Base-64 is constrained by the alphabet size: every codeword has the same length, so it carries zero redundancy with respect to its own alphabet (the Kraft sum is exactly 1), and the source distribution plays no role in its design.
What all of them share with Huffman codes is the prefix-free (self-synchronizing) property from the first section of this page: a decoder scanning left to right can always tell where one codeword ends and the next begins.
-
ASCII (7 bits) is a fixed-length code over 128 symbols: every character costs the same, so its redundancy equals for the actual text distribution.
-
UTF-8 is a variable-length, prefix-free code over the full Unicode range. Common ASCII characters (which dominate real text) get 1 byte; rarer code points get 2–4 bytes. The leading bits of each byte (
0,110,1110,11110) signal the length, and continuation bytes start with10, so no encoding is a prefix of another and a decoder can resynchronize from any byte boundary. -
Base-32 (RFC 4648) is a fixed-length code: 5 bits per character over a 32-character alphabet (A–Z, 2–7). The binding constraint is the alphabet, not the distribution: 32 is the largest power of two that fits in a case-insensitive, unambiguous printable alphabet.
-
Base-64 is a fixed-length code: 6 bits per character over a 64-character alphabet (A–Z, a–z, 0–9, +, /). Again the constraint is the alphabet: 64 is the largest power of two that fits in printable ASCII, making it the most compact text-safe binary encoding. Padding with
=aligns the output to 4-character blocks.
Details
The shared principle: prefix-freeness. For UTF-8, the leading-bit pattern (0 for 1 byte, 110 for 2, 1110 for 3, 11110 for 4, with continuation bytes 10xxxxxx) makes the set of encodings prefix-free: no code point’s byte sequence is a prefix of another’s. A decoder that hits a corrupt or resyncs mid-stream can determine the length of the next code point from the first byte alone, without any external length field — the same greedy first-match decoding as the binary prefix tree in the first section.
The contrast: fixed-length, zero-redundancy codes. Base-32 and Base-64 do not exploit any source distribution: every character carries exactly 5 or 6 bits, all or codewords are used, and the Kraft sum is exactly 1. Their redundancy with respect to their own alphabet is zero; the only “loss” is the mapping itself, which inflates the data by (Base-32) or (Base-64) plus padding, because 8-bit bytes do not align with 5- or 6-bit groups. They exist to carry binary data through channels that only safely transmit a restricted printable alphabet (email, URLs, JSON), not to compress.
Where the entropy idea does apply: UTF-8’s expected length on real text is close to 1 byte per character precisely because ASCII-range code points dominate — a skewed distribution exploited by a variable-length code, the same mechanism Huffman formalizes. ASCII, being fixed-length, cannot do this: its 7 bits per character are spent uniformly whether the text is full of e or of z.
Base-64 in practice: used in MIME email attachments, JWT tokens, and data URIs.
Interactive exploration §
Example problem §
Quizz
Problem: A source emits 4 symbols with probabilities . Compute the entropy, build the Huffman code, compute its expected length, and compare it with the entropy bound.
How to solve
- Compute the entropy with . None of the probabilities is a power of 2, so expect a non-integer value.
- Run the Huffman algorithm: repeatedly merge the two least-probable nodes. Watch the tie at 0.3 (the merged node and the original 0.3 symbol).
- Read the codewords off the tree, compute , and check the Kraft sum.
- Compare with : the gap must satisfy (source coding theorem). Here the probabilities are not powers of 2, so the Huffman code cannot reach exactly — each must be an integer at least as large as .
Solution
Entropy: bits/symbol.
Huffman code:
- Merge 0.1 + 0.2 → 0.3
- Merge 0.3 (symbol) + 0.3 (merged node) → 0.6
- Merge 0.4 + 0.6 → 1.0
- Codewords: symbol 0.4 →
0(1 bit), symbol 0.3 →10(2 bits), symbol 0.2 →110(3 bits), symbol 0.1 →111(3 bits).
Expected length: bits/symbol.
Gap: bits, which satisfies . Unlike the power-of-2 distribution , here the Huffman code does not reach the entropy bound exactly: lengths must be integers, so a little code space is necessarily wasted.
Kraft check: . ✓ (full tree, no code space wasted).
Redundancy: .