Run-length encoding
The simplest compression there is: replace a stretch of identical values with a count and one copy. One row of pixels shows when it shrinks data and when it doubles it.
In 30 seconds
Run-length encoding compresses data by storing each run, a stretch of identical values, as two numbers: how many, and of what. Sixteen pixels in three runs become six numbers.
Decoding writes each value out again the stated number of times, so nothing is lost.
It only works when runs are long. Data that changes at every step comes out bigger, because every single value now carries a count. That is why it suits fax pages, flat-colour images and repetitive database columns, and not photographs or text.
Run-length encoding, step by step
Sizes are counted in stored numbers, with one number per pixel. Real formats pack counts and values into bytes or bits, and cap the length of a run at what a count can hold.
- Step 1: A row of pixels. A small picture is a grid of pixels, and the plain way to store it is one number per pixel. Look at one row: sixteen numbers, yet almost every pixel is the same as its neighbour. That repetition is wasted space.
- Step 2: Find the runs. A run is a stretch of identical values side by side. Reading the row left to right, the value changes only twice, so the sixteen pixels fall into just three runs: five empty, six blue, five empty.
- Step 3: Store count and value. Run-length encoding writes each run as a pair: how many, and of what. Three runs need six numbers where the raw row needed sixteen. Done row by row, the whole picture shrinks from 112 numbers to 34.
- Step 4: Decode it back. Decoding reads each pair and writes the value out that many times. The row comes back exactly, pixel for pixel. Nothing was approximated or thrown away, which is what lossless compression means.
- Step 5: When it backfires. Now a row where the value flips at every pixel. Each run has length one, so every pixel costs two numbers, a count of 1 and its value. The output is twice the size of the input. Run-length encoding only helps data that actually has long runs.
- Step 6: Mixing runs and raw. Practical formats add an escape. A leading number says either “repeat the next value this many times” or “copy the next few values as they are”. Busy stretches then cost one extra number instead of doubling. PackBits, used in TIFF files, and the compressed modes of BMP and TGA images work this way.
- Step 7: Where it is used. Run-length encoding earns its place wherever data repeats: fax pages that are mostly white, icons with flat colours, the long strings of zeros inside a JPEG, and database columns holding the same value many times in a row. It is often one stage inside a larger compressor rather than the whole method.
Try it yourself
Learn this first
Nothing. This concept starts from scratch.
Spotted a mistake on this page?