What are varints in Protocol Buffers and why does protobuf use zigzag encoding for signed integers?
Last updated
A varint encodes an integer in 1 to 10 bytes: 7 data bits per byte plus a continuation bit, so small numbers take few bytes.
With plain
int32, negatives are sign-extended to 64 bits, so -1 always costs 10 bytes.Zigzag (used by
sint32/sint64) maps 0→0, -1→1, 1→2, -2→3, keeping small negatives short. Use it when values are often negative.