16. Variable-Length Integer Encoding
16. Variable-Length Integer Encoding
QUIC packets and frames commonly use a variable-length encoding for non-negative integer values. This encoding ensures that smaller integer values need fewer bytes to encode.
The QUIC variable-length integer encoding reserves the two most significant bits of the first byte to encode the base 2 logarithm of the integer encoding length in bytes. The integer value is encoded on the remaining bits, in network byte order.
This means that integers are encoded in 1, 2, 4, or 8 bytes and can encode 6-, 14-, 30-, or 62-bit values respectively. Table 4 summarizes the encoding properties.
| 2Bit | Length | Usable Bits | Range |
|---|---|---|---|
| 00 | 1 | 6 | 0-63 |
| 01 | 2 | 14 | 0-16383 |
| 10 | 4 | 30 | 0-1073741823 |
| 11 | 8 | 62 | 0-4611686018427387903 |
Table 4: Summary of Integer Encodings
For example, the eight-byte sequence 0xc2 0x19 0x7c 0x5e 0xff 0x14 0xe8 0x8c (in hexadecimal) decodes to the decimal value 151288809941952652; the four-byte sequence 0x9d 0x7f 0x3e 0x7d decodes to 494878333; the two-byte sequence 0x7b 0xbd decodes to 15293; and the single byte 0x25 decodes to 37 (as does the two-byte sequence 0x40 0x25).
Values do not need to be encoded in the minimum number of bytes necessary.
An endpoint MAY use values that are larger than strictly necessary to encode a value. For instance, a two-byte encoding could be used to encode values less than 64.
Versions (Section 15), packet numbers sent in the header (Section 17.1), and frame types (Section 19) are all described using integers, but do not use this encoding.