AI Glossary / MLOps and deployment / Beginner

Run-length encoding

Definition

Run-length encoding, or RLE, is a lossless compression technique that replaces a consecutive sequence of repeated values with a description of the value and how many times it occurs. It is particularly useful when neighboring data items often remain the same.

What it means

Instead of storing AAAAAA as six separate letters, a simple RLE format can store “six copies of A.” The word consecutive is essential: separated occurrences of A do not form one run. A sequence alternating A and B has repetition, but it has no long runs of identical symbols.

RLE is a family of encoding schemes rather than one universal file format. Formats differ in how they represent counts, literal data and control markers. The basic idea is easy to understand, but a decoder still needs the exact format rules to reconstruct the intended sequence.

How it works

Scan the input in order and count successive equal values. When the value changes or the maximum allowed count is reached, output a run description and begin another. A decoder reads each description and writes the specified number of copies.

Real formats may combine run descriptions with literal blocks that store varied data directly. This avoids paying a count-and-value overhead for every isolated symbol. They may also specify row endings, maximum run lengths, padding and escape commands.

For binary data, another convention stores alternating run lengths with an agreed starting value. That convention needs different framing from explicit value-and-count pairs. Both use runs, but their byte streams are not interchangeable.

Three practical examples

1. Image masks: a segmentation mask containing broad regions of background can have long runs when scanned in a specified order. RLE can represent the mask while preserving every pixel label.

2. Status histories: a regularly sampled machine-state sequence may stay “idle” for many samples. A count can replace those repeated state values, provided the sampling interval and ordering remain known.

3. Raster graphics: some bitmap formats combine repeated color-index runs with literal segments. The decoder also needs dimensions, palette information and the format's control rules to render the correct image.

Think of it this way

Think of a meeting note saying “the next eight responses were yes” instead of writing yes eight times. The note preserves order and repetition with fewer repeated words.

The analogy has limits: a digital format must distinguish counts from values unambiguously. It cannot rely on a person's interpretation of punctuation, and a run of one item may take more space than the item itself.

Worked example

Use an illustrative byte format where every pair contains one count byte followed by one value byte. Counts range from 1 to 255; ignore headers for this calculation. The input AAAAABBBCC contains ten one-byte symbols.

Its runs are five As, three Bs and two Cs, so the encoded pairs are (5,A), (3,B), (2,C). Three pairs occupy six bytes. Relative to ten input bytes, the payload saving is four bytes, or 40 percent. Decoding expands the counts to recover the original ten symbols exactly.

Now try ABABABABAB. It contains ten runs of length one, so the same pair-only format requires twenty bytes. It doubles the payload size. A format offering literal blocks could handle this case more efficiently, but its control overhead must also be counted.

Finally, a run of 300 As cannot fit in one count byte under these rules. Split it into (255,A) and (45,A), requiring four bytes. These are teaching-format calculations, not a claim about a particular bitmap format's complete file size or permitted control values.

Illustrative case study

Fictional case: MaskShelf stores AI-generated object masks. An initial prototype compresses each row independently and achieves compact representations on large, simple shapes.

During exchange with another tool, the reconstructed masks appear rotated or misplaced. Both programs decode run counts correctly, but they disagree about the order in which pixels are visited. One traverses rows; the other traverses columns.

The team documents dimensions, traversal order, starting label and row-boundary policy. It verifies masks with asymmetric test shapes and checks that decoded pixel counts match the declared dimensions. This fictional example shows why a correct sequence of counts is insufficient without a shared interpretation of the array.

Common misconceptions and mistakes

“RLE compresses any repetitive data well.” It exploits consecutive repetitions. Repeated phrases or alternating symbols may need different techniques.

“Sorting first is a free improvement.” Sorting can create longer runs, but it changes order. If order matters, the information needed to restore it must be stored and counted.

“All RLE formats are compatible.” Count conventions, special values, scan order and literal modes vary. A generic description cannot replace a format specification.

“RLE removes image detail.” Basic RLE preserves the exact encoded values. A separate quantization or resizing stage may be lossy, but that is not an inherent part of run encoding.

Business use

RLE can be a straightforward option for masks, labels and other data with long constant regions. Before adopting it, inspect run-length distributions on actual production inputs, including fragmented masks and noisy sequences. Compare complete stored size against a simple uncompressed baseline and established compression tools.

For applications that need random access, assess whether an index or per-row boundaries are necessary and include their cost. Decoders should reject invalid counts and prevent expansion beyond the declared output size. Record the format version and traversal convention so archived data remains interpretable when software changes.

People also ask

Is RLE always smaller than the original?

No. Short runs can expand the data. Some formats provide literal modes or an uncompressed fallback to limit that problem.

Can RLE represent more than two values?

Yes. Explicit value-and-count schemes can represent many symbols. Alternating-run conventions are often tailored to binary or otherwise structured data.

Can an RLE mask be used in an AI workflow?

Yes, as a storage or interchange representation. The receiving process must reconstruct or otherwise handle the exact mask convention; RLE itself is not a learned model.

Check your understanding

Two files contain the same number of As and Bs. One groups identical letters together; the other alternates them. Must pair-based RLE give equal sizes?

Answer: No. Size depends on consecutive runs, not just symbol totals. The grouped file generally needs fewer run descriptions under the same format.

Related terms

  • Lossless compression
  • Recursive indexing
  • Entropy coding
  • segmentation mask
  • raster image
  • literal encoding
  • bitmap compression

Learn next

Encode a few short strings by hand, then compare explicit pairs with alternating binary run lengths. Study a published format's literal and escape rules, and test reconstruction on empty inputs, maximum counts and asymmetric images.

More in MLOps and deployment

  • Re-Pair - Re-Pair, short for recursive pairing, is a lossless grammar-based compression method that repeatedly replaces a frequent adjacent pair of symbols with a new...
  • Reassignment method - The reassignment method is a signal-analysis technique that relocates values in a time - frequency or time - scale representation to better estimated...
  • Recommender System - A recommender system selects or orders items that may be useful or relevant to a user in a particular context.
  • Sardinas - Patterson algorithm - The Sardinas - Patterson algorithm determines whether a finite set of variable-length codewords is uniquely decodable.
  • SDCH - SDCH stands for Shared Dictionary Compression over HTTP.
  • Sequitur algorithm - Sequitur is an incremental algorithm that discovers repeated structure in a sequence of discrete symbols by building a hierarchical grammar.

Sources

Primary specification example: Microsoft's “Bitmap Compression” documents BI_RLE8 and BI_RLE4 modes, including runs, literals and control escapes: https://learn.microsoft.com/en-us/windows/win32/gdi/bitmap-compression . The pair-only byte example and fictional mask scenario are original illustrations and do not reproduce those formats.

Previous: Rules extraction system family Next: Ruzzo - Tompa algorithm

  • Home
  • Daily AI Updates
  • Blog
  • AIFBL Academy
  • AI Glossary
  • Products and Tools
  • Store
  • Free CFO AI Prompt Pack
  • About Shihan Sheriff
  • Privacy Policy
  • Terms of Use
  • Refund Policy
  • Cookie Policy
  • Earnings Disclaimer