1. 程式人生 > >結構體定義:unsigned int type : 2;

結構體定義:unsigned int type : 2;

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個位元組