encodeZigZag32 function
ZigZag-encodes a signed 32-bit integer.
Maps signed values to unsigned values so that values with small absolute magnitude have small varint encodings: 0 → 0, -1 → 1, 1 → 2, -2 → 3, 2 → 4, …
Formula: (n << 1) ^ (n >> 31)
The arithmetic right shift (>>) propagates the sign bit, producing
either all-zeros (positive) or all-ones (negative), which the XOR then
uses to flip or preserve the shifted bits.
Implementation
int encodeZigZag32(int n) {
return (n << 1) ^ (n >> 31);
}