Posts MQTT V3.1.1学习笔记(剩余长度编码规则)
Post
Cancel

MQTT V3.1.1学习笔记(剩余长度编码规则)

固定报头中的剩余长度是指当前数据包中剩余的字节数,包括可变报头及有效荷载。剩余长度字段从第二个字节起,数据储存遵循大端模式(高字节在前,低字节在后)。对于长度小于等于127个字节的消息,可变程度编码方案使用一个单独的字节。长度大于127个字节的消息,使用如下方案处理:每个字节的最低的7位编码数据(最大为127),最高位用来指明还有后续字节。可变长度区域所用的最大字节数为4。能代表的最大的数为268,435,455(256MB),编码为:0xFF,0xFF,0xFF,0x7F。

编码、解码的C语言实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include "stdio.h"
#include "stdint.h"

void encoding(int a)
{
	int digit = 0;
	printf("\t");
	do
	{
		digit = a % 128;
		a = a / 128;
		if(a > 0)
		{
			digit = digit | 0x80;
		}
		if(digit <= 0x0f)
			printf("0x0%X ",digit);
		else
			printf("0x%X ", digit);
	}
	while(a > 0);
	printf("\n");
}

void decoding(uint8_t * array)
{
	int multiplier = 1;
	int value = 0, digit = 0;
	do
	{
		digit = *(array++);
		value += (digit & 127) * multiplier;
		multiplier *= 128;
	}
	while((digit & 128) != 0);
	printf("\t%d\n", value);
}

int main()
{
	int a = 0;
	uint8_t code[] = {0xFF, 0xFF, 0xFF, 0x7F};
	printf("Encode a decimal number (X) into the variable length encoding:\n");
	printf("\tPlease input a integer:");
	fflush( stdout );
	scanf("%d", &a);
	encoding(a);
	fflush( stdout );
	printf("Decode the remaining length field(0xFF, 0xFF, 0xFF, 0x7F):\n");
	decoding(code);
	return 0;
}

输出如下:

1
2
3
4
5
Encode a decimal number (X) into the variable length encoding:
	Please input a integer:128
	0x80 0x01 
Decode the remaining length field(0xFF, 0xFF, 0xFF, 0x7F):
	268435455
This post is licensed under CC BY 4.0 by the author.