位段:结构体定义:unsigned int type : 2;

#include "stdio.h"

int main(void)
{
	typedef union
	{
		unsigned char byte;	                /**< the whole byte */
		struct
		{
			unsigned int retain : 1;		/**< retained flag bit */
			unsigned int qos : 2;				/**< QoS value, 0, 1 or 2 */
			unsigned int dup : 1;				/**< DUP flag bit */
			unsigned int type : 4;			/**< message type nibble */
		} bits;
 	} MQTTHeader;
 	MQTTHeader xxx;
 	xxx.byte = 0xD0;
 	printf("MQTTHeader.bits.retain = %d\r\n",xxx.bits.retain);
 	printf("MQTTHeader.bits.qos = %d\r\n",xxx.bits.qos);
 	printf("MQTTHeader.bits.dup = %d\r\n",xxx.bits.dup);
 	printf("MQTTHeader.bits.type = %d\r\n",xxx.bits.type);
}

运行结果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190805141325841.png
结论:
unsigned int retain : 1;表示为unsigned int的第0位,
unsigned int qos : 2; 表示为unsigned int的第1、2位;
unsigned int dup : 1;表示为unsigned int的第3位;
unsigned int type : 4;表示unsigned int的第4、5、6、7位。

猜你喜欢

转载自blog.csdn.net/qq_37733540/article/details/98484493