[英]C++ Bitfield Struct size definition (Why is it packed larger?)
我對C ++中的位打包有疑問。
可以說我們有一個用C ++定義的結構。 在下面:
typedef struct
{
unsigned long byte_half : 4; //0.5
unsigned long byte_oneAndHalf : 12; //2
union
{
unsigned long byte_union_one_1 : 8; //3
unsigned long byte_union_one_2 : 8; //3
unsigned long byte_union_one_3 : 8; //3
};
unsigned long byte_one : 8; //4
}LongStruct;
這是一個稱為LongStruct的結構。 從它的外觀來看,它占用4個字節,並且很長。 現在,我執行以下行:
int size = sizeof(LongStruct);
我看一下大小,期望它的值為4。結果我得到的是12。 我以什么方式錯誤地可視化了我的結構?
預先感謝您能給我的任何幫助。
匿名聯合並沒有替代其屬性,而是在您的位字段結構中間占據了一個四字節的塊。 因此,您的前兩個成員是兩個字節+兩個填充。 那么您的並集是一個字節加三個填充。 然后,您的最終成員是一個字節,再加上三個填充。 總數是您觀察到的12。
我將嘗試深入研究該標准,以確切了解其對匿名聯合位域的說明。 另外,如果您描述了您要解決的實際問題,我們也可以考慮回答。
順便說一句,您已將此標記為C ++,因此非常喜歡struct X {};
超過typedef struct {} X;
union
擴展為long
,因此其大小為4個字節,而不是1個字節。
結果,它與結構開頭的偏移量對齊為4個字節。
另外,整個結構被擴展為4個字節的倍數。
因此,實際結構如下所示:
unsigned long byte_half : 4; // bits 0 - 3
unsigned long byte_oneAndHalf : 12; // bits 4 - 15
unsigned long byte_padding_1 : 16; // bits 16 - 31 // align union
union
{
unsigned long byte_union_one_1 : 8; // bits 32 - 39
unsigned long byte_union_one_2 : 8; // bits 32 - 39
unsigned long byte_union_one_3 : 8; // bits 32 - 39
unsigned long byte_padding_2 : 24; // bits 40 - 63 // expand union
};
unsigned long byte_one : 8; // bits 64 - 71
unsigned long byte_padding_3 : 24; // bits 72 - 95 // expand structure
因此,總大小為96位(12個字節)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.