Search

Search papers and lessons

Lossless Compression

Level 2 · 10 min read

Lossless compression shrinks data by giving common symbols short codes and rare ones long codes, and entropy sets the limit on how far this can go.

On this page

  • Colour = topic mix
  • Discrete math
  • Probability
  • Calculus
  • Information theory
  • Sign in to see your progress

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 ii has Probability pip_i and its code has ℓi\ell_i bits, the average length is

L=∑ipi ℓi.L = \sum_i p_i \, \ell_i.

Each code word is weighted by how often it is used. That is the link to Expected Value: LL is the expected code length of one symbol.

The math

Definition: Entropy of a source

For a source whose symbols have probabilities p1,…,pnp_1, \ldots, p_n, the entropy in bits is

H=−∑ipilog⁡2pi.H = -\sum_i p_i \log_2 p_i.

Here pip_i is the probability of symbol ii, and log⁡2\log_2 is the base-2 Logarithm, so HH is measured in bits. Symbols with pi=0p_i = 0 contribute nothing.

Entropy is the average surprise of a symbol. A symbol with probability pp carries log⁡2(1/p)\log_2(1/p) 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,

L≥H.L \ge H.

No scheme can beat the entropy on average. Shannon also showed that codes exist which come within one bit of it, that is H≤L<H+1H \le L < H + 1. Huffman's method, described below, is one such code.

0.20.40.60.800.20.40.60.81pbits per symbol
  • H(p) for a two-symbol source
Entropy of a two-symbol source. It peaks at 1 bit when p is one half and falls toward 0 as one symbol becomes certain.

Building a code: the Huffman method

David Huffman's 1952 method builds a prefix code from the probabilities:

  1. List each symbol with its probability as a leaf (an end point of a tree).
  2. Take the two smallest weights, join them under a new node, and give that node the sum of their weights.
  3. Repeat until one node is left. This is the Binary Tree: every node has at most two branches.
  4. Read off each code: a left branch is 0, a right branch is 1. The depth of a leaf is its code length.

Frequent symbols end up near the top of the tree, with short codes.

Worked examples

Example
Four symbols with dyadic probabilities

Setup. A source emits A, B, C, D with probabilities 1/21/2, 1/41/4, 1/81/8, 1/81/8.

  1. Entropy: H=12log⁡22+14log⁡24+18log⁡28+18log⁡28H = \tfrac{1}{2}\log_2 2 + \tfrac{1}{4}\log_2 4 + \tfrac{1}{8}\log_2 8 + \tfrac{1}{8}\log_2 8.
  2. Each log is a whole number: 11, 22, 33, 33. So H=0.5+0.5+0.375+0.375=1.75H = 0.5 + 0.5 + 0.375 + 0.375 = 1.75 bits.
  3. Huffman builds the code A=0A = 0, B=10B = 10, C=110C = 110, D=111D = 111. The code lengths are 1,2,3,31, 2, 3, 3.
  4. Average length: L=0.5×1+0.25×2+0.125×3+0.125×3=1.75L = 0.5 \times 1 + 0.25 \times 2 + 0.125 \times 3 + 0.125 \times 3 = 1.75 bits.
  5. 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.

Example
The word ABRACADABRA

Setup. The word has 11 letters. Counts: A 5 times, B 2 times, R 2 times, C 1 time, D 1 time.

  1. Probabilities: 5/115/11, 2/112/11, 2/112/11, 1/111/11, 1/111/11.
  2. Entropy, term by term: 511log⁡2115≈0.517\tfrac{5}{11}\log_2 \tfrac{11}{5} \approx 0.517; the two 2/112/11 terms give 2×0.447=0.8942 \times 0.447 = 0.894; the two 1/111/11 terms give 2×0.314=0.6292 \times 0.314 = 0.629.
  3. Total: H≈2.04H \approx 2.04 bits per letter.
  4. Huffman merges CC with DD (weight 2), then BB with RR (weight 4), then the weight-2 pair with the weight-4 pair (weight 6), then AA (weight 5) with that (weight 11). The code lengths are AA: 1, and BB, RR, CC, DD: 3 each.
  5. Average length: L=(5⋅1+2⋅3+2⋅3+1⋅3+1⋅3)/11=23/11≈2.09L = (5 \cdot 1 + 2 \cdot 3 + 2 \cdot 3 + 1 \cdot 3 + 1 \cdot 3) / 11 = 23/11 \approx 2.09 bits.
  6. Check the bound: H=2.04≤L=2.09<H+1H = 2.04 \le L = 2.09 < H + 1.
  7. 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.

Example
A realistic case: a DNA sequence

Setup. A DNA sequence uses four bases with frequencies AA: 0.3, TT: 0.3, CC: 0.2, GG: 0.2. Sequencing files often store these as two bits each.

  1. Entropy: H=2×0.3log⁡210.3+2×0.2log⁡210.2≈2×0.521+2×0.464=1.971H = 2 \times 0.3 \log_2 \tfrac{1}{0.3} + 2 \times 0.2 \log_2 \tfrac{1}{0.2} \approx 2 \times 0.521 + 2 \times 0.464 = 1.971 bits per base.
  2. Huffman merges CC with GG (weight 0.4), then AA with TT (weight 0.6), then the two halves. Every leaf sits at depth 2, so each base costs exactly 2 bits.
  3. The Huffman code therefore saves nothing over the plain two-bit code, even though the entropy says 1.97 bits is possible.
  4. 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

SituationWhat goes wrongBetter choice
The frequencies are unknown or change during the fileA fixed code table fits the wrong statisticsAdaptive coding, which updates the table as it reads
The data has long repeats, such as text or logsPer-symbol codes miss repeats across many symbols[[dictionary-method
The symbols are nearly equally likely, such as DNAHuffman gives no gain over fixed-length codesContext modelling (predicting each symbol from the ones just before it), or coding whole blocks
The data is already compressed or encryptedEntropy is close to the maximum, so the output cannot shrinkStore it as is
You need the gap closed to the last fraction of a bitHuffman wastes up to one bit per symbolArithmetic 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 H=12log⁡22+14log⁡24+14log⁡24=0.5+0.5+0.5=1.5H = \tfrac{1}{2}\log_2 2 + \tfrac{1}{4}\log_2 4 + \tfrac{1}{4}\log_2 4 = 0.5 + 0.5 + 0.5 = 1.5 bits. Shannon's bound says no lossless code can average less than 1.5 bits per symbol, and the Huffman code 00, 1010, 1111 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 log⁡24=2\log_2 4 = 2 bits. Each probability is 1/41/4, 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 8−3.2=4.88 - 3.2 = 4.8 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