关于MQTT 3.1.1连接报文Keep Alive字节格式的技术问询
Let's break this down clearly—your confusion about translating time intervals to the 16-bit Keep Alive field is totally reasonable, since binary byte splitting can feel opaque at first.
Core Background on the Keep Alive Field
First, remember: the Keep Alive value is a 16-bit unsigned integer stored in big-endian format (most significant byte, or MSB, comes first). To get the byte structure for any interval, you just need to split the total number of seconds into two 8-bit segments: the high byte (MSB) and low byte (LSB).
How to Represent a 10-Minute Interval
10 minutes equals 600 seconds. Here's how to convert that to the required byte structure:
- Convert 600 to hexadecimal:
600 = 0x258 - Split this into the high and low 8-bit parts:
- MSB (first byte):
0x02→ binary00000010 - LSB (second byte):
0x58→ binary01011000
- MSB (first byte):
So your Keep Alive bytes would look like this:
- Keep Alive MSB: 0 0 0 0 0 0 1 0
- Keep Alive LSB: 0 1 0 1 1 0 0 0
Confirming the Maximum Keep Alive Interval
You’re spot-on about the maximum value! 65535 is the largest number a 16-bit unsigned integer can hold (since 2^16 - 1 = 65535). This translates to 16 consecutive 1s in binary, which splits into two 8-bit bytes of all 1s:
- Keep Alive MSB: 1 1 1 1 1 1 1 1 (decimal 255)
- Keep Alive LSB: 1 1 1 1 1 1 1 1 (decimal 255)
As you noted, this equals roughly 18 hours (65535 ÷ 3600 ≈ 18.2), which aligns perfectly with the MQTT 3.1.1 specification.
内容的提问来源于stack exchange,提问作者Boris Deletic

