Work on the source support, so its listed probabilities are positive; zero-probability symbols may be omitted. An optimal binary prefix code minimizes the expected codeword length for that distribution. The same optimal expected length is attained when optimization is over uniquely decipherable codes, by the converse and existence parts of Kraft–McMillan inequality.
Choose Shannon lengths . They satisfy , so the preceding existence theorem gives a prefix code with those lengths. Also for every symbol, including the integer cases. Thus its expected length is less than . An optimal code cannot have a larger expected length, proving
For a deterministic one-symbol source the empty word has length zero, consistent with this bound.
A compact code or optimal prefix code minimizes the expected codeword length for the given source probabilities and coding alphabet. The relevant comparison here is among binary prefix codes. The minimum is also the minimum among uniquely decodable codes, since the Kraft-McMillan inequality permits every uniquely decodable length list to be realized by a prefix code with the same lengths.
Put and let be the largest length. Expanding sums over all strings of source symbols, where is the total code length. By unique decodability, the concatenations of length in this sum are all distinct, so there are at most of them. Since ,
Taking th roots and sending to infinity proves the Kraft–McMillan inequality
Now is a probability distribution. With base-two logarithms, Gibbs inequality gives
Terms with contribute zero. Therefore
The normalization by is important: the raw numbers need not sum to one.
A uniquely decodable code is a map whose extension by concatenation to finite strings is injective. Write for its codeword lengths and assume the target alphabet has size . The Kraft–McMillan inequality gives . The Gibbs inequality says for probability distributions , with the usual convention for zero probabilities.
Set . For Shannon entropy , the Gibbs inequality becomes
Since , the entropy lower bound for prefix codes also applies to this uniquely decodable code: