The MySQL Protocol has a set of possible encodings for integers:
Fixed-length integers
Length-encoded integers
Protocol::FixedLengthInteger
A fixed-length integer stores its value in a series of bytes with the least significant byte first.
Example
A int<3> with the value
1
is stored as:
01 00 00
Protocol::LengthEncodedInteger
An integer that consumes 1, 3, 4, or 9 bytes, depending on its numeric value
To convert a number value into a length-encoded integer:
If the value is < 251, it is stored as a 1-byte integer.
If the value is ≥ 251 and < (216), it is stored as
fc
+ 2-byte integer.If the value is ≥ (216) and < (224), it is stored as
fd
+ 3-byte integer.If the value is ≥ (224) and < (264) it is stored as
fe
+ 8-byte integer.
Up to MySQL 3.22, 0xfe
was followed by
a 4-byte integer.
To convert a length-encoded integer into its numeric value, check the first byte:
If it is < 0xfb, treat it as a 1-byte integer.
If it is 0xfc, it is followed by a 2-byte integer.
If it is 0xfd, it is followed by a 3-byte integer.
If it is 0xfe, it is followed by a 8-byte integer.
If the first byte of a packet is a length-encoded integer
and its byte value is 0xfe
, you must
check the length of the packet to verify that it has
enough space for a 8-byte integer.
If not, it may be an
EOF_Packet
instead.
Depending on the context, the first byte may also have other meanings:
If it is 0xfb, it is represents a
NULL
in aProtocolText::ResultsetRow
.If it is 0xff and is the first byte of an
ERR_Packet
0xff
as the first byte of a
length-encoded integer is undefined.
Implemented By
Example
fa -- 250 fc fb 00 -- 251