StringMash.com

Run-length encoding

Runs of the same character become a count and the character.

Conversion
28 characters
Updates as you type
Encoded12W1B12W3B
Length28 → 10

Show the steps
  1. 4 runs: 12 × W, 1 × B, 12 × W, 3 × B.
  2. 28 characters became 10. Run-length encoding only saves space when characters repeat in long runs, as in simple images; on ordinary text it often makes things longer.

Using it

Type or paste text. Each run of the same character becomes its length and the character: WWWWBBB is 4W3B. The rows compare the length before and after. Swap the boxes to expand a code such as 12W1B12W3B back into text.

This form writes the count every time, even for a run of 1, so it can be decoded without any guessing. It can't take text with digits in, because a digit would be read as part of a count.

A worked example

Take AAAABBBCCD. There are four runs: 4 A, 3 B, 2 C and 1 D. Write each count before its letter and you get 4A3B2C1D, 8 characters for 10. Decoding reads a number, then repeats the letter after it that many times.

Now take Hello. Only the double l is a run, so the code is 1H1e2l1o, 8 characters for 5. The sample on this page, 28 characters like a row of pixels from a black-and-white image, comes out as 12W1B12W3B: 10 characters. Runs are what RLE needs, and pictures have them where writing doesn't.

When it helps

Run-length encoding is the simplest compression there is, and it only pays off when the data has long runs: rows of one color in a simple image, the white space on a faxed page. Ordinary writing rarely has two of the same letter in a row, so coding it this way usually doubles its length. Try a sentence and see.

Formats that use it include PackBits, Apple's scheme for MacPaint, and the TGA and PCX image formats. Fax machines combine it with Huffman coding, giving short codes to the run lengths that turn up most.

Questions

What is AAABBC in run-length encoding?

3A2B1C.

Is RLE lossless?

Yes. Decoding gives back exactly what went in.

Why did my text get longer?

Each single character became two: a 1 and the character. RLE only shrinks data that repeats in runs.

How are counts above 9 written?

In full: twelve W's are 12W. The decoder reads every digit up to the next letter as one number, which is why this form can't encode text that has digits in it.

Sources

Added . Last updated and reviewed . What's new