Embedded HandbookApps
All sections › IX. The C language: from basics to advanced
STM32F103, STM32F407, STM32G031 · level intermediate · 10 min read
Open in the interactive handbook

76о. Lossless compression on a microcontroller: RLE, deltas and LZSS with a small window for display frames and logs

Pictures for a display take Flash, a sensor log takes pages of external memory, a radio transfer takes airtime. Lossless compression wins on all three, but on a microcontroller it has its own rules: no malloc, no spare kilobytes for a dictionary, and the decoder often works on data that came over a link — and must survive a corrupted archive. Here are three simple techniques that fit into a couple of hundred bytes of code: runs (RLE), deltas for slow quantities and LZSS with a 256-byte window — and a measurement of what each gives on a display frame, a temperature log, a text log and random bytes.

Grounds: alg.c was built with gcc 12.2.0 on a computer (stm-sys:1) and run by host.c: four kinds of data, each compressed and decompressed back with a byte-by-byte comparison; 20000 corrupted archives fed to the decoders with a check for writing past the buffer. The same alg.c was built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F and Cortex-M0.

Terms used in the documentation

Term Meaning
lossless compression decompression gives back the original bytes
PackBits an RLE variant with a "literals or repeat" control byte
LZSS, LZ77 compression by references back to bytes already seen
back-reference (offset, length) a reference back: the offset and length of a match
search window, dictionary how many bytes back the encoder looks
flag byte a byte of flags: literal or reference for the next eight items
delta encoding of samples writing samples as differences from the previous one
compression ratio the archive size relative to the original
incompressible data, expansion data that does not compress and grows when "compressed"

In plain words. RLE writes "128 zeros" instead of 128 zeros. LZSS writes "repeat 12 bytes seen 40 bytes ago" instead of the bytes themselves. Deltas turn a slowly rising temperature into a row of small numbers that compress well. Nothing compresses random data — and you have to be able to survive that.


76о.1 What to compress on a microcontroller and why

In all three cases the decoder matters more than the encoder: it runs on the device, must be small, must not ask for memory beyond the output buffer and must not crash on a corrupted input.

76о.2 RLE: runs in the PackBits style

The control byte says what follows: 0…127 — that many plus one bytes "as is", 129…255 — one byte repeated 2 to 128 times. The decoder is a few lines:

size_t rle_unpack(const uint8_t *in, size_t n, uint8_t *out, size_t cap)
{
    size_t i = 0, o = 0;
    while (i < n) {
        uint8_t c = in[i++];
        if (c < 128) {
            size_t lit = (size_t)c + 1;
            if (i + lit > n || o + lit > cap)
                return 0;
            memcpy(out + o, in + i, lit);
            i += lit;
            o += lit;
        } else if (c > 128) {
            size_t run = 257u - c;
            if (i >= n || o + run > cap)
                return 0;
            memset(out + o, in[i++], run);
            o += run;
        }
    }
    return o;
}

Two checks per item — do not read past the end of the input and do not write past the end of the output — are what make the decoder safe (76о.8). A run starts at three equal bytes: two equal bytes are cheaper left among literals, otherwise every pair breaks a literal block with an extra control byte. Then the worst case is known in advance: on data without runs the archive is larger than the original by one byte per 128.

76о.3 Deltas: slow quantities into small numbers

A temperature in hundredths of a degree changes by units per sample, and the values themselves — 2300, 2301, 2299… — do not repeat in two bytes. The difference from the previous sample fits into one byte; a rare large jump is written as the marker 0x80 and the full value:

        int d = x[k] - prev;
        prev = x[k];
        if (d >= -127 && d <= 127) {
            out[o++] = (uint8_t)(int8_t)d;
        } else {
            out[o++] = 0x80;
            out[o++] = (uint8_t)x[k];
            out[o++] = (uint8_t)((uint16_t)x[k] >> 8);
        }

The first sample always goes as a full value — its difference from zero is large. This is not compression in itself but preparation: after it the data has repeats that LZSS finds.

76о.4 LZSS: references back in a 256-byte window

For each position the encoder looks in the last 256 bytes for the longest match of 3 to 18 bytes. Found — it writes a two-byte reference (offset − 1 and length − 3), not found — the byte itself. A flag byte before every eight items says which is which. The decoder keeps no window of its own — it copies from the output already decoded:

                size_t off = (size_t)in[i] + 1, len = (size_t)in[i + 1] + LZ_MIN;
                i += 2;
                if (off > o || o + len > cap)
                    return 0;
                for (size_t k = 0; k < len; k++, o++) /* по байту: ссылка может перекрывать сама себя */
                    out[o] = out[o - off];

Copying byte by byte rather than with memcpy is mandatory: the reference "repeat 18 bytes starting 1 byte back" is a run of one byte, and it reads what it has just written itself.

The encoder here searches the whole window — slowly (up to 256 × 18 comparisons per position) but simply; for compressing on a computer at build time that is enough. Fast encoders keep a hash table on three bytes (section 76д), but the decoder does not change.

LZSS bytes: flags, literals and references back in the window

76о.5 Experiment: four kinds of data

Data bytes RLE LZSS
frame SSD1306 128×64 1024 233 193
temperature log, as is 2048 2057 1536
temperature log, deltas 2048 1960 990
temperature log, one-byte deltas 1026 1029 829
text log 2016 2030 688
random bytes 1024 1032 1152

Every row was decompressed back and compared byte by byte — no differences.

76о.6 The worst case: an archive larger than the source

On incompressible data RLE grows by 1/128, LZSS by 1/8. The archive buffer must be sized for the worst case: for 1024 bytes — 1032 for RLE and 1152 for LZSS. For a log it is sensible to keep a "not compressed" flag and write the block as is if the archive came out no smaller than the source.

76о.7 Code sizes on Cortex-M4F and Cortex-M0

Function Cortex-M4F, bytes Cortex-M0, bytes
rle_pack 192 196
rle_unpack 144 130
delta8_encode 92 88
delta8_decode 106 82
lz_pack 236 262
lz_unpack 178 222

The LZSS decoder is 178 bytes of code and zero bytes of RAM beyond the output buffer. RLE calls memcpy and memset from the library, LZSS calls nothing. For comparison: DEFLATE decompression (the zlib format) needs a 32 KB window and Huffman tables — on a small chip that is more than all of RAM.

76о.8 A corrupted archive: the decoder does not leave the buffer

An archive received over radio or read from damaged Flash can be any garbage. The decoders were fed 20000 random inputs of up to 300 bytes with a 600-byte output buffer and guard bytes right after it. Not a single guard byte changed; 19691 inputs out of 20000 were rejected — the function returned 0. The other 309 decoded "into something": a format without a checksum cannot tell garbage from data, so an archive over a link is always sent with a CRC (section 43.1), and the decoder is left with one job — not to leave its bounds.

76о.9 Compression and a Flash log together

A log is written in blocks: a page of samples is collected in RAM — compressed — written with a header "length, method, CRC". Compressing by blocks rather than the whole log gives two things: a power loss spoils only the last block, and any block can be read without decompressing all the previous ones. The price is that the LZSS window starts anew in every block, and the first tens of bytes compress worse.

76о.10 Pitfalls

memcpy in LZSS decoding. When a reference overlaps its own output, memcpy may copy anything — copy byte by byte (76о.4).

An archive buffer "the size of the source". Random data grew by 128 bytes out of 1024 — the buffer will overflow (76о.6).

RLE for a log of 16-bit numbers. Alternating low and high bytes kill the runs: 2048 → 2057 (76о.5). Deltas in one byte first.

A decoder without checks. Two checks per item — and 20000 corrupted inputs never took it past the buffer (76о.8). Without them the first broken packet writes into someone else's memory.

Compression instead of integrity. Decompressing without an error does not mean the data is right: 309 random inputs decompressed. A CRC is needed.


76о.11 Summary

Check yourself

  1. Why does RLE not compress a log of 16-bit temperatures? - A) The temperature changes too fast - B) Low and high bytes alternate, and there are no long runs of equal bytes - C) RLE works only with text - D) The log is too short
  2. Why does the LZSS decoder copy byte by byte rather than with memcpy? - A) It is faster - B) There is no memcpy in a microcontroller's standard library - C) A reference may overlap its own output and read bytes just written - D) So as not to leave the buffer
  3. What protects against a corrupted archive received over radio? - A) Bounds checks in the decoder — against leaving the buffer, and a CRC — against wrong data - B) The LZSS format itself - C) Compression makes data resistant to errors - D) Nothing is needed, the decoder will notice the error itself

Check yourself: answers - 1 — B. Why: 2048 bytes became 2057 with RLE; one-byte deltas solve this (76о.5). - 2 — C. Why: "Repeat 18 bytes from 1 byte back" is a run, it reads itself (76о.4). - 3 — A. Why: Of 20000 garbage inputs 309 decompressed without an error — only a CRC can tell them apart (76о.8).

Next: section 76п "A table with linear interpolation instead of a formula: a uniform grid, binary search, how many nodes are needed and what logf costs" — how to replace a logarithm with a table and choose the number of nodes.

Open in the interactive handbook