如何使用位字段struct和union制作4个字节?

时间:2018-08-15 07:46:04

标签: c++ visual-studio-2017 unions bit-fields

这是代码。

struct test {
    struct abc {
        int a : 24;
        union b {
            int b1 : 10;
            int b2 : 14;
        };
    };
    int c : 8;
};

我想使abc结构为3字节大小,再加上一个额外的1字节大小的变量以使结构为4字节结构。但是,由于内部结构实际上显示为4个字节,结构测试的总大小为5个字节。

我正在使用Visual Studio 2017版本。 (而且我也已经使用打包选项)

如何将结构调整为4个字节?这是已经在使用中的代码中发现的错误,因此依赖项太大,以至于我无法更改变量的顺序或在其中创建新的结构。

1 个答案:

答案 0 :(得分:2)

#pragma pack(1)
struct test {
    struct abc {
        short a;
        union b {
            byte b1;
            byte b2;
        }_b;
    }_abc;
    byte c;
};

enter image description here

相关问题