Technopedia

The technologist’s encyclopedia

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: ⌈log⁡2∣X∣⌉\lceil \log_2 |\mathcal{X}| \rceil 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 ⌈log⁡2∣X∣⌉\lceil \log_2 |\mathcal{X}| \rceil 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:

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.

Prefix-free code as a binary tree: symbols are leaves 0 1 0 1 0 1 A B C D 0 10 110 111 root

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):

  1. Decode the bit string 100110111.
  2. Is the code {A = 0, C = 01} prefix-free? Why not, and what does it break?
Solution
  1. Scan left to right, stopping at the first codeword match: 10 → B, then 0 → A, then 110 → C, then 111 → D. The string decodes to B A C D. The first-match rule is unambiguous precisely because the code is prefix-free.
  2. No: 0 is a prefix of 01. The string 01 could be a single C or an A followed by a 1-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 xx with probability p(x)p(x) is I(x)=−log⁡2p(x)I(x) = -\log_2 p(x) bits.

The entropy of a discrete random variable XX with distribution pp is:

H(X)=−∑xp(x)log⁡2p(x)H(X) = -\sum_x p(x) \log_2 p(x)

Entropy is the average self-information and the lower bound on the expected code length of any lossless prefix-free code.

Details

Properties:

Mutual information: I(X;Y)=H(X)−H(X∣Y)=∑x,yp(x,y)log⁡2p(x,y)p(x)p(y)≥0I(X; Y) = H(X) - H(X|Y) = \sum_{x,y} p(x,y) \log_2 \frac{p(x,y)}{p(x)p(y)} \geq 0. It measures how much knowing YY reduces uncertainty about XX.

Conditional entropy: H(X∣Y)=∑yp(y)H(X∣Y=y)H(X|Y) = \sum_y p(y) H(X|Y=y). The number of bits still needed to describe XX after observing YY.

All logarithms in this page are base 2, so all quantities are in bits.

Example: English text has entropy ≈0.6\approx 0.6–1.31.3 bits/character over a 27-character alphabet (26 letters + space), versus log⁡227≈4.75\log_2 27 \approx 4.75 bits for a uniform distribution. The achievable compression ratio is therefore 0.6/4.75≈130.6/4.75 \approx 13% to 1.3/4.75≈271.3/4.75 \approx 27% 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:

R=1−H(X)log⁡2∣X∣R = 1 - \frac{H(X)}{\log_2 |\mathcal{X}|}

A uniform source has R=0R = 0 (no waste); a highly skewed source has RR close to 1 (most of the code space is unused).

Details

For English text (27-character alphabet, H≈1.0H \approx 1.0 bits/char as a midpoint): R≈1−1.0/4.75≈79R \approx 1 - 1.0/4.75 \approx 79%. 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 l1,l2,…,lnl_1, l_2, \ldots, l_n is realizable as a binary prefix-free code if and only if:

∑i=1n2−li≤1\sum_{i=1}^{n} 2^{-l_i} \leq 1

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 lil_i occupies a subtree of size 2−li2^{-l_i} of the full binary tree. The Kraft inequality says these subtrees must be disjoint (total area ≤1\leq 1). 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 ll claims a rectangle of area 2−l2^{-l}. 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.

Kraft inequality: codewords tile the unit code space 0 (area 1/2) 10 (1/4) 110 (1/8) 111 (1/8) total area = 1/2 + 1/4 + 1/8 + 1/8 = 1 (Kraft sum)

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 H(X)H(X), and any prefix-free code with expected codeword length LL:

H(X)≤L<H(X)+1H(X) \leq L < H(X) + 1

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 nn (encoding nn-tuples of symbols), the gap shrinks to 1/n1/n per symbol, so the bound is asymptotically tight.

Details

Lower bound (L≥H(X)L \geq H(X)):

Let lil_i be the codeword length for symbol xix_i with probability pip_i. By the Kraft inequality, ∑i2−li≤1\sum_i 2^{-l_i} \leq 1. Define qi=2−liq_i = 2^{-l_i}; then ∑iqi≤1\sum_i q_i \leq 1. Extend to a proper distribution by adding a dummy symbol with probability 1−∑iqi1 - \sum_i q_i.

By the Gibbs inequality (relative entropy is non-negative):

∑ipilog⁡21pi≤∑ipilog⁡21qi\sum_i p_i \log_2 \frac{1}{p_i} \leq \sum_i p_i \log_2 \frac{1}{q_i}

Since qi=2−liq_i = 2^{-l_i}, the right side is ∑ipili=L\sum_i p_i l_i = L. The left side is H(X)H(X). Hence H(X)≤LH(X) \leq L.

Upper bound (L<H(X)+1L < H(X) + 1):

Choose codeword lengths li=⌈−log⁡2pi⌉l_i = \lceil -\log_2 p_i \rceil. Then li<−log⁡2pi+1l_i < -\log_2 p_i + 1, so:

L=∑ipili<∑ipi(−log⁡2pi+1)=H(X)+1L = \sum_i p_i l_i < \sum_i p_i(-\log_2 p_i + 1) = H(X) + 1

It remains to verify the Kraft inequality. Since li=⌈−log⁡2pi⌉l_i = \lceil -\log_2 p_i \rceil by definition, the first sum is exactly:

∑i2−li=∑i2−⌈−log⁡2pi⌉≤∑i2−log⁡2pi=∑ipi=1\sum_i 2^{-l_i} = \sum_i 2^{-\lceil -\log_2 p_i \rceil} \leq \sum_i 2^{-\log_2 p_i} = \sum_i p_i = 1

where the single inequality uses ⌈y⌉≥y\lceil y \rceil \geq y, hence 2−⌈y⌉≤2−y2^{-\lceil y \rceil} \leq 2^{-y}. So the lengths are realizable, and a prefix-free code with expected length <H(X)+1< H(X) + 1 exists.

Typical-set intuition: the theorem has a purely combinatorial reading. For a sequence of nn i.i.d. symbols, the law of large numbers concentrates almost all probability mass on the typical set: roughly 2nH(X)2^{nH(X)} sequences, each with probability close to 2−nH(X)2^{-nH(X)}. Indexing one typical sequence therefore takes about log⁡22nH(X)=nH(X)\log_2 2^{nH(X)} = nH(X) bits, i.e. H(X)H(X) 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 nn symbols shrinks the gap to 1/n1/n 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:

  1. Start with a leaf node for each symbol, weighted by its probability.
  2. Repeatedly merge the two least-probable nodes into a new parent node whose probability is the sum.
  3. Assign bit 0 to one child and bit 1 to the other at each merge.
  4. 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 H(X)≤LHuffman<H(X)+1H(X) \leq L_{\text{Huffman}} < H(X) + 1, and the gap LHuffman−H(X)L_{\text{Huffman}} - H(X) 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 ∑pili\sum p_i l_i.

Huffman construction, step by step, for p = (A: 0.5, B: 0.25, C: 0.125, D: 0.125)
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 n−1n-1 symbols, and the greedy choice is locally optimal at every step.

Example: probabilities (0.5,0.25,0.125,0.125)(0.5, 0.25, 0.125, 0.125) (the distribution animated in the diagram above).

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 [0,1)[0, 1) 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:

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.

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 252^5 or 262^6 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 8/5=1.68/5 = 1.6 (Base-32) or 8/6≈1.338/6 \approx 1.33 (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 (0.4,0.3,0.2,0.1)(0.4, 0.3, 0.2, 0.1). Compute the entropy, build the Huffman code, compute its expected length, and compare it with the entropy bound.

How to solve
  1. Compute the entropy with H=−∑ipilog⁡2piH = -\sum_i p_i \log_2 p_i. None of the probabilities is a power of 2, so expect a non-integer value.
  2. 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).
  3. Read the codewords off the tree, compute L=∑ipiliL = \sum_i p_i l_i, and check the Kraft sum.
  4. Compare LL with HH: the gap must satisfy 0≤L−H<10 \leq L - H < 1 (source coding theorem). Here the probabilities are not powers of 2, so the Huffman code cannot reach HH exactly — each lil_i must be an integer at least as large as −log⁡2pi-\log_2 p_i.
Solution

Entropy: H=−(0.4log⁡20.4+0.3log⁡20.3+0.2log⁡20.2+0.1log⁡20.1)H = -(0.4 \log_2 0.4 + 0.3 \log_2 0.3 + 0.2 \log_2 0.2 + 0.1 \log_2 0.1) ≈0.529+0.521+0.464+0.332=1.846\approx 0.529 + 0.521 + 0.464 + 0.332 = 1.846 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: L=0.4(1)+0.3(2)+0.2(3)+0.1(3)=0.4+0.6+0.6+0.3=1.9L = 0.4(1) + 0.3(2) + 0.2(3) + 0.1(3) = 0.4 + 0.6 + 0.6 + 0.3 = 1.9 bits/symbol.

Gap: L−H=1.9−1.846=0.054L - H = 1.9 - 1.846 = 0.054 bits, which satisfies 0<L−H<10 < L - H < 1. Unlike the power-of-2 distribution (0.5,0.25,0.125,0.125)(0.5, 0.25, 0.125, 0.125), 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: 2−1+2−2+2−3+2−3=0.5+0.25+0.125+0.125=1≤12^{-1} + 2^{-2} + 2^{-3} + 2^{-3} = 0.5 + 0.25 + 0.125 + 0.125 = 1 \leq 1. ✓ (full tree, no code space wasted).

Redundancy: R=1−H/log⁡24=1−1.846/2≈0.077=7.7R = 1 - H/\log_2 4 = 1 - 1.846/2 \approx 0.077 = 7.7%.