AQA GCSE Computer Science (8525), section 3.3.8 (Data compression)
The idea
Run length encoding (RLE) is a lossless method that works well when the same value is repeated many times in a row. Instead of storing every repeated value, it stores a pair: how many times (the frequency), and the value.
Example with text
AAAABBBCCD becomes 4A 3B 2C 1D: 10 characters become 4 pairs.
Example with bits
A row of a bitmap: 0000011100000011
- Five 0s, three 1s, six 0s, two 1s.
- Encoded as frequency/data pairs: 5 0, 3 1, 6 0, 2 1, or
5 0 3 1 6 0 2 1.
Decoding
Expand each pair: 5 0 3 1 6 0 2 1 becomes 00000 111 000000 11 = 0000011100000011.
Bitmap example
Each row is encoded in turn.
When it works well, and when it does not
| Works well | Works badly |
|---|---|
| images with large blocks of the same colour (logos, cartoons) | photographs, where neighbouring pixels differ |
| long runs of the same value | data with no repeats, such as ABCDEF, which becomes 1A 1B 1C 1D 1E 1F and is larger |
Why use it?
It is simple, lossless, and reduces file size when there are long runs.
Common mistake: counting the runs wrongly, or forgetting that a single value still needs a pair, such as 1 D. Also, RLE can make a file bigger if there are few repeats.
Exam tip: write the pairs as frequency then value, with the same order as the original data. Check by decoding your answer to see if you get the original.
Check yourself
Write 0000111 using RLE frequency/data pairs.
4 0 3 1.
Decode 3 1 2 0 1 1.
Why is RLE unsuitable for a photograph?
Neighbouring pixels usually differ, so there are few runs and the encoded file may not be smaller.