MQTT Protocol Length Field Encoding

MQTT is a relatively new MQ protocol for communication between distributed systems based on messages (message oriented middleware).

MQTT has been jointly developed by Eurotech and IBM as a future standard protocol for Internet of Things and M2M scenarios. OASIS has adopted the standard (published as version 3.1 under so future updates to the protocol will take place under OASIS’ auspices.

The idea of MQTT is simple: Sensor and actor nodes and applications communicate through message queues (topics in MQ speak). This setup has a very low coupling between the nodes and apps. The only thing apps and nodes need to know in order to exchange data is the address and topic of a message broker.

MQTT was designed for devices with very limited capabilities such as battery-driven sensor nodes and wireless devices. This implies that the protocol needs to be very efficient (low protocol overhead) because any excess byte transmitted over a wireless link would consume precious battery capacity. As a consequence, many fields in the MQTT protocol are optional, so they are only transmitted when needed.

Another interesting field is the remaining length field indicating the actual length of an MQTT message. The length of the remaining length field is between 1 and 4 bytes depending on the payload size (the actual user message).

The most significant bit of a remaining length field byte has the meaning «continuation bit» (CB). If more bytes follow, it is set to 1. Remaining length is encoded as a * 128^0 + b * 128^1 + c * 128^2 + d * 128^3 and placed into the RL field bytes as follows:

MQTT remaining length field              encoding

MQTT remaining length field encoding

MSB: Most Significant Byte
LSB: Least Significant Byte

The following examples show the encoding for single byte (1) and multi-byte remaining field lengths (2).

Example 1: RL = 364 = 108*128^0+2*128^1, a=108, CB0=1, b=2, CB1=0 (c, d, CB2=0)

Example 2: RL = 25’897 = 41*128^0 + 74*128^1 + 1*128^2, a=41, CB0=1, b=74, CB1=1, c=1, (CB2, d=0)

The encoding of the remaining length field requires a bit of additional bit and byte handling, but the benefit is that only a single byte is needed for most messages while preserving the capability to send larger message up to 268’435’455 bytes.

See more details on the MQTT protocol in this slide presentation.

Dieser Beitrag wurde unter Uncategorized veröffentlicht. Setze ein Lesezeichen auf den Permalink.

Die Kommentarfunktion ist geschlossen.