TL;DR
Lossless compression makes a file smaller without losing a single bit, so the original can be rebuilt exactly. The trick is to give frequent symbols short codes and rare symbols long codes, so the average message needs fewer bits than a fixed-length code would use.
There is a hard floor. The Entropy of the source, measured in bits per symbol, is the smallest average code length any lossless scheme can reach.
Where you'll see it: ZIP and gzip files, PNG images, FLAC audio, and the sequence files that store DNA readings.
Intuition
Start from a question you already know
Think about Morse code. The most common letter in English, E, is a single dot. Rare letters such as Q or Z take four symbols. Morse gave short codes to common letters, and that is the same idea a file compressor uses: the things you say most often should cost the least to say.
Now the question is precise. Suppose a source (anything that emits a stream of symbols, such as letters in a text file) produces symbols with known frequencies. How short can the average code get, and how do you build a code that gets there?
The simplest version: two symbols
Imagine a sensor that reports either 0 or 1 each second. A bit is one binary digit, 0 or 1 (see Binary Numbers (Bits and Bytes)). If both values are equally likely, you cannot do better than one bit per reading. The message is as unpredictable as it can be.
Now make 1 rare: it appears one time in ten. You can store the common 0 as a single bit and spend more bits only on the rare 1. Over a long stream the average cost falls well below one bit per reading, because most readings are the cheap kind. That falling average is the whole idea of compression.
A code is a list of bit strings
A prefix code assigns each symbol a bit string, with the rule that no code is the beginning of another. If A is 0 and B is 10, then the reader sees a 0 and knows it is an A at once. It never has to wait for more bits to decide. Prefix codes can be decoded one bit at a time, which is why almost every practical scheme uses them.
Here is a tiny example. Encode the word ABA with A = 0, B = 10: the output is 0 10 0, which is the bits 0100. Decode from the left: 0 is A, 10 is B, 0 is A. Done.
Why the average matters
A compressor does not care about one symbol. It cares about the average length over the whole message. If symbol has Probability and its code has bits, the average length is
Each code word is weighted by how often it is used. That is the link to Expected Value: is the expected code length of one symbol.
The math
For a source whose symbols have probabilities , the entropy in bits is
Here is the probability of symbol , and is the base-2 Logarithm, so is measured in bits. Symbols with contribute nothing.
Entropy is the average surprise of a symbol. A symbol with probability carries bits of surprise: one half carries 1 bit, one quarter carries 2 bits.
The limit: Shannon's source coding bound
Claude Shannon proved in 1948 (see A Mathematical Theory of Communication) that for any lossless code,
No scheme can beat the entropy on average. Shannon also showed that codes exist which come within one bit of it, that is . Huffman's method, described below, is one such code.
- H(p) for a two-symbol source
Building a code: the Huffman method
David Huffman's 1952 method builds a prefix code from the probabilities:
- List each symbol with its probability as a leaf (an end point of a tree).
- Take the two smallest weights, join them under a new node, and give that node the sum of their weights.
- Repeat until one node is left. This is the Binary Tree: every node has at most two branches.
- Read off each code: a left branch is
0, a right branch is1. The depth of a leaf is its code length.
Frequent symbols end up near the top of the tree, with short codes.
Worked examples
Setup. A source emits A, B, C, D with probabilities , , , .
- Entropy: .
- Each log is a whole number: , , , . So bits.
- Huffman builds the code , , , . The code lengths are .
- Average length: bits.
- A fixed two-bit code would spend 2 bits on every symbol.
Interpretation. Here the Huffman code hits the entropy exactly, because every probability is a power of one half. It saves 0.25 bits per symbol, about 12.5 percent.
Setup. The word has 11 letters. Counts: A 5 times, B 2 times, R 2 times, C 1 time, D 1 time.
- Probabilities: , , , , .
- Entropy, term by term: ; the two terms give ; the two terms give .
- Total: bits per letter.
- Huffman merges with (weight 2), then with (weight 4), then the weight-2 pair with the weight-4 pair (weight 6), then (weight 5) with that (weight 11). The code lengths are : 1, and , , , : 3 each.
- Average length: bits.
- Check the bound: .
- The whole word takes 23 bits. A fixed three-bit code (enough for five symbols) takes 33 bits, and plain ASCII takes 88 bits.
Interpretation. The frequent A costs one bit, and the rare letters cost three. Huffman is not exactly at the entropy here, but it is within one bit of it, as the theory promises.
Setup. A DNA sequence uses four bases with frequencies : 0.3, : 0.3, : 0.2, : 0.2. Sequencing files often store these as two bits each.
- Entropy: bits per base.
- Huffman merges with (weight 0.4), then with (weight 0.6), then the two halves. Every leaf sits at depth 2, so each base costs exactly 2 bits.
- The Huffman code therefore saves nothing over the plain two-bit code, even though the entropy says 1.97 bits is possible.
- The gap of 0.03 bits per base is real but small: about 1.5 percent.
Interpretation. Symbol-by-symbol coding can only use the single-symbol frequencies. To get below that, a compressor must look at longer patterns, which is what general-purpose tools do. Arithmetic coding can approach the entropy of a message, not just of one symbol.
Tradeoffs and failure modes
| Situation | What goes wrong | Better choice |
|---|---|---|
| The frequencies are unknown or change during the file | A fixed code table fits the wrong statistics | Adaptive coding, which updates the table as it reads |
| The data has long repeats, such as text or logs | Per-symbol codes miss repeats across many symbols | [[dictionary-method |
| The symbols are nearly equally likely, such as DNA | Huffman gives no gain over fixed-length codes | Context modelling (predicting each symbol from the ones just before it), or coding whole blocks |
| The data is already compressed or encrypted | Entropy is close to the maximum, so the output cannot shrink | Store it as is |
| You need the gap closed to the last fraction of a bit | Huffman wastes up to one bit per symbol | Arithmetic coding, which encodes a whole message as one number and so avoids the whole-bit rounding per symbol |
The table has a common thread. Entropy is a property of the source model, not of the file. A better model of the source gives a lower entropy and smaller output. Shrinking further always means knowing more about the data.
History
Claude Shannon's 1948 paper, A Mathematical Theory of Communication, set out the entropy limit and showed that codes can approach it. He was working on telephone and telegraph channels at Bell Labs, and his question was how many bits a message truly needs.
David Huffman, then a graduate student at MIT, developed his method in 1951-52 while working on the problem of finding the best prefix code, and published it in 1952. It gives the shortest possible prefix code for a known set of frequencies and was quickly adopted. It is still used inside many formats today, often in combination with dictionary methods.
Recap
Lossless compression exploits the fact that real data is not uniformly random. Entropy tells you the floor on average code length. Prefix codes such as Huffman's come within one bit of that floor for single symbols. Better compression comes from modelling longer patterns, which is where dictionary and arithmetic methods take over.
Check yourself
QuestionWhat is the minimum average code length, in bits per symbol, for a source with probabilities 1/2, 1/4, 1/4?Show answer
The entropy is bits. Shannon's bound says no lossless code can average less than 1.5 bits per symbol, and the Huffman code , , reaches exactly 1.5.
QuestionA source has four equally likely symbols. What is its entropy, and what does Huffman coding produce?Show answer
Entropy is bits. Each probability is , so the Huffman tree is balanced and every code is two bits long. Huffman gives no gain over a fixed two-bit code, because the source has no skew to exploit.
QuestionWhy is a prefix code easy to decode, and what would break if one code were a prefix of another?Show answer
A reader can decode bit by bit and emit a symbol as soon as the bits read so far match a code word. If A were 1 and B were 10, the reader seeing 1 could not tell whether it was A or the start of B, so it would have to look ahead, and ambiguity could arise.
QuestionA text file has 1,000 symbols with entropy 3.2 bits each. Roughly how many bits can any lossless scheme save at best, and why is the answer not exact?Show answer
Compared with an 8-bit fixed code, the entropy bound allows about bits saved per symbol, or about 4,800 bits in total. This assumes the symbol frequencies are known and independent of position. Real files have patterns across symbols, so a model that captures them can beat this figure, while a model that misses them cannot reach it.
QuestionYou compress a file with a Huffman code built from the whole file's statistics. Why must the decoder also receive the code table?Show answer
The decoder needs the same tree to map bit strings back to symbols. Without the table, the bits are meaningless. Storing the table costs bits too, so very small files may not shrink at all.
Sources
- Shannon, C. E. (1948). A Mathematical Theory of Communication. doi
- Huffman, D. A. (1952). A Method for the Construction of Minimum-Redundancy Codes. doi
- Lossless compression (Wikipedia)
- Huffman coding (Wikipedia)