ZigZag encoding
ZigZag encoding maps signed integers to unsigned integers so that values near zero remain small before variable-length encoding.
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
Citations
- Protocol Buffers encoding: Base 128 Varints and Signed Integers
- Apache Avro 1.12.0: Binary Encoding and writer schemas
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.