ZigZag Encode
ZigZag encoding maps a signed integer to an unsigned one (0→0, -1→1, 1→2, -2→3, ...), and is paired with Varint for compact coding.
Purpose
It makes small negative numbers as compact as small positive ones under variable-length coding.
Mechanism
The formula: n ≥ 0 → 2n, and n < 0 → 2|n| - 1. In bit operations: (n << 1) ^ (n >> 31).
Use cases
- Protobuf sint encoding
- Compact signed serialization