C++ Bitfield Struct size definition(为什么打包得更大?)

标签 c++ struct unions bit-fields

我对 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/

相关文章:

c - 将2个结构作为参数传递给C中的pthread

c++ - 使用毫秒而不是在 C++ 中使用秒来休眠线程

c++ - 如何修复警告 "the compiler can assume that the address of ' 对象“永远不会为 NULL”

c++ - 为什么空基类也是成员变量时禁止空基优化?

c++ - union 与位掩码和位移位

c++ - 在没有重载的情况下在 Union 上进行类型转换重载 +=

c - 具有 union 静态和动态字符数组的结构

c++ - 返回引用之外的单例生命周期

openCL 内核中的复杂结构

c++ - 为什么结构的 sizeof 不等于每个成员的 sizeof 之和?