zigzag-encoding · also Zig-zag encoding

ZigZag encoding

ZigZag encoding maps signed integers to unsigned integers so that values near zero remain small before variable-length encoding.

Related Observatory article: Read on hesela.com

Mapping: Use 2n for nonnegative n and -2n-1 for negative n. This maps 0, -1, 1, -2, 2 to 0, 1, 2, 3, 4. The mapping precedes byte encoding; it is not byte order or encryption. [1]

Declared types: Protobuf sint32 and sint64 use ZigZag; int32 and int64 do not, and their negative values require ten varint bytes. The schema changes the interpretation. [1]

Avro: Binary int and long use variable-length ZigZag coding: -64 becomes hexadecimal 7f, while 64 becomes 80 01. Readers also need the writer schema. [2]

Arithmetic: A signed 64-bit minimum maps to the unsigned 64-bit maximum. Implement the formula within the intended width; language-specific shifts and overflow need explicit handling. [1]

Relations

related
Variable-length integer, Data serialization, Stream VByte, Rice coding, Protocol Buffers

Citations

  1. Protocol Buffers encoding: Base 128 Varints and Signed Integers (accessed 2026-11-17)
  2. Apache Avro 1.12.0: Binary Encoding and writer schemas (accessed 2026-11-17)
Sources & caveats
  • Source synthesis and exact integer examples, not a full serializer or a native decoder conformance test.
  • Executable examples and controls: https://hesela.dev/research/varint-contracts.mjs and https://hesela.dev/research/varint-contracts.test.mjs.

JSON: /data/terms/zigzag-encoding.json

Published by Hesela team · Updated

Report a correction · Editorial standards · Reuse guidance

Cite this page
Hesela team. ZigZag encoding. Hesela. 2026-11-21. https://hesela.dev/terms/zigzag-encoding/