1. C语言实现的HTTP协议的解析源码中有下面的结构体定义:
struct http_parser {
unsigned int type : 2;
unsigned int flags : 8;
unsigned int state : 7;
unsigned int header_state : 7;
unsigned int index : 7;
unsigned int lenient_http_headers : 1;
unsigned int nread;
unsigned int content_length;
unsigned short http_major;
unsigned short http_minor;
unsigned int status_code : 16;
unsigned int method : 8;
unsigned int http_errno : 7;
unsigned int upgrade : 1;
void *data;
};
当前运行环境是Windows7 64位运行环境
unsigned int字节长度是4,unsigned short字节长度是2,void *字节长度是4
如果没有使用unsigned int type : 2;这种声明方法,sizeof(struct http_parser) = 12 * 4 + 2 * 2 + 4 = 56
现在这种实现:sizeof(struct http_parser) = 4 + 8 + 4 + 4 + 4 = 24
2. 理解
unsigned int type : 2; 表示type变量使用unsinged int 32位中的低两位。
该结构体中的前5个字段总共占用4个字节