Varint
Wire type 0 (Varint) encodes integers using a variable-length encoding where each byte contributes 7 bits of value. The most significant bit of each byte is a continuation flag: 1 means more bytes follow, 0 means this is the last byte. Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum.
Used For
Encoding Details
Varint is the most compact integer encoding in Protocol Buffers. Small values (0-127) encode in a single byte. Larger values use more bytes only as needed.
Encoding algorithm: take the integer, split into 7-bit groups from LSB to MSB. For each group except the last, set the MSB to 1 (continuation). For the last group, MSB = 0.
Example: value 300 = 0b100101100 Group 1 (LSB): 0101100 = 0x2c → add continuation bit → 0xac Group 2 (MSB): 0000010 = 0x02 → last byte → 0x02 Encoded: 0xac 0x02
Signed integers (sint32, sint64) use zigzag encoding to avoid large varint for negative numbers: n >= 0 → 2n, n < 0 → 2(-n)-1. This maps -1 → 1, -2 → 3, keeping negative numbers small.
Examples
| Label | Hex | Explanation |
|---|---|---|
| Field 1, value 1 | 08 01 | Tag 0x08 = field 1, wire 0. Value 0x01 = 1. |
| Field 1, value 150 | 08 96 01 | Tag 0x08. Value 150: 0x96=0b10010110 (cont), 0x01=0b00000001. 7-bit groups: 0010110 + 0000001 = 0b10010110. |
| bool true | 08 01 | bool field 1 = true (varint 1). false = varint 0. |
| sint32 -1 (zigzag) | 08 01 | sint32 -1 → zigzag → 1 → varint 0x01. |
| sint32 -2 (zigzag) | 08 03 | sint32 -2 → zigzag → 3 → varint 0x03. |