Understanding the run-length encoding tool — concept and principle
Run-length encoding (RLE) replaces each run of identical consecutive characters with a count followed by the character. This tool encodes your text and shows the compression ratio. RLE is one of the simplest lossless compression methods and appears in fax transmission, early bitmap formats such as PCX and BMP's RLE modes, and as a stage inside more complex codecs.
How it is calculated
- Encoded: the text is scanned for maximal runs of one repeated character; each run of length n of character c is written as "n" followed by "c".
- Compression ratio = original length ÷ encoded length (in characters).
A ratio above 1 means the output is shorter than the input; below 1 means RLE made it longer. Every run is encoded, including runs of length 1, which become "1x".
The principle
When data contains long stretches of the same value, as in a scanned page that is mostly white or a simple graphic, storing "how many" plus "what" is far shorter than repeating the value. Each run costs a fixed amount (here the digits of the count plus one symbol), so the gain grows with run length. Conversely, text with few repeats, such as normal prose, roughly doubles in size because each single character turns into two.
Worked example
- Input: "WWWWWWBBBWWWW", 13 characters.
- Runs: 6 × W, 3 × B, 4 × W.
- Encoded: 6W3B4W, which is 6 characters.
- Ratio: 13 ÷ 6 = 2.166666667.
How to read the result
A ratio of about 2.17 means the encoded text is less than half the original length. Values well above 1 indicate long runs; values near 0.5 indicate almost no repetition. As a rule, RLE in this form only pays off when the average run is longer than two characters.
Common mistakes
- Encoding text that contains digits: "3A" in the input becomes "13" + "1A", and the output can no longer be decoded unambiguously.
- Expecting RLE to compress ordinary words; most letters appear once in a row.
- Comparing ratios between tools that use different formats (some write runs of 1 without a count, or use a byte count with a cap such as 255).
Frequently asked questions
How do you decode RLE?
Read the number, then repeat the next character that many times, and continue to the end. "6W3B4W" gives WWWWWW BBB WWWW.
Is run-length encoding lossless?
Yes, as long as the format is unambiguous, decoding returns exactly the original data.
Where is RLE still used today?
In fax (ITU-T T.4), in some image formats, and as a step in JPEG, where runs of zero coefficients are coded together.
Sources: ITU-T Recommendation T.4, Standardization of Group 3 facsimile terminals · K. Sayood, Introduction to Data Compression, Morgan Kaufmann