我对 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个字节,并且适合一个long。现在我执行以下行:
int size = sizeof(LongStruct);
我看了一下大小,期望它的值为 4。结果我得到的是 12。我以何种方式错误地可视化了我的结构?
预先感谢您能给我的任何帮助。
最佳答案
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 字节)。
关于C++ Bitfield Struct size definition(为什么打包得更大?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24639435/