Run-Length Encoding by Example

Run-length encoding records a repeated symbol and the length of its consecutive run.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a short message
  2. Check an expanding input
  3. Encode consecutive repetitions while retaining order
  4. Include the storage size of the count fields

Trace a short message

AAAABB becomes the records (A,4) and (B,2). Decoding repeats A four times and B twice. See counting consecutive symbol runs.

Check an expanding input

An alternating sequence has run length one everywhere. Adding count fields can then use more space than storing the input directly. What a compressed size includes explains why headers and counts matter.[1][2]

Encode consecutive repetitions while retaining order

The sequence A A A B B A can be represented by run pairs (A,3),(B,2),(A,1). A single count of four As would lose the split around the B block. Decoding expands the pairs in their stored order. See counting symbol runs.

Input AAABBA
Run starts at first A, ends when B arrives
Flush final A as a length-one run
Decode → AAABBA

Include the storage size of the count fields

A stream alternating A and B creates one count per symbol, which can cost more than writing raw symbols. Test a final singleton and an empty stream, and reject invalid run lengths under the format.

References

  1. Claude E. Shannon, A Mathematical Theory of Communication ↩
  2. David J. C. MacKay, Information Theory, Inference, and Learning Algorithms ↩