Codes and signals
How compression shrinks a message
A computer normally stores every letter in 8 bits, whether it’s a common letter or a rare one. Compression finds the patterns in a message and stores it in fewer bits, and the message comes back exactly, with nothing lost. Type your own message, or pick one below, and every part of the page works on it: counting its letters, building the codes, reading the bits back, and finding repeats.
1. Every letter costs 8 bits
Inside a computer, text is stored as numbers, and each number as 8 bits (one byte). The letter s is number 115, which is 01110011. Every letter gets the same 8 bits, even the very common ones.
2. Some letters are common
Most messages use only a few different letters, and use some of them far more than others. That is the pattern compression feeds on: if the common letters had shorter codes, the whole message would be shorter.
3. Building the codes
In 1952, a student named David Huffman found the best way to give letters codes of different lengths. Start with one pile per letter. Then keep joining the two smallest piles into one, until everything is in one tree. Each letter’s code is the path from the top of the tree down to it: 0 for left, 1 for right.
4. Reading it back
Here is your whole message as one stream of bits, with nothing between the letters. To read it, start at the top of the tree and follow each bit: left for 0, right for 1. When you reach a letter, write it down and jump back to the top.
Why no gaps are needed. In a tree like this, every letter sits at the end of a branch, never part way along one, so no letter’s code is the start of another letter’s code. That means there is only ever one way to read the bits. Codes made up by hand can go wrong here: if e were 0, s were 01 and h were 1, the bits 01 could mean s, or e then h.
5. Repeats
Short codes help with common letters, but real text also repeats whole words and phrases. Another trick, found by Abraham Lempel and Jacob Ziv in 1977, is to write each repeat as a copy of something earlier: “go back 7 letters and copy 4”. Tap a copy to see where it comes from.
a copywhat it copies
6. Why some things won’t shrink
So why not compress a file, then compress the result, again and again, until it is tiny? Because no method can shrink every message. A simple count shows why. Each message must turn into a different shorter one, or there would be no way to get the right one back. But there aren’t enough shorter messages to go round.