C中的Bitfields和Unions给出了问题

use*_*904 3 c struct unions bit-fields

我正在实施无线电标准,并在结构和内存大小方面遇到了问题.在下面的例子中,我需要这个结构位于单个字节的内存中(按照无线电标准),但它目前给我2个字节的大小.经过多次挖掘后,我明白这是因为联盟的"大小"是字节而不是3位......但是还没有解决这个问题.我看过:

但似乎都没有给我一个解决方案.

有任何想法吗?

谢谢!

#ifdef WIN32
#pragma pack(push)
#pragma pack(1)
#endif

typedef struct three_bit_struct
{
    unsigned char bit_a : 1;
    unsigned char bit_b : 1;
    unsigned char bit_c : 1;
}three_bit_struct_T;


typedef union
{
    three_bit_struct_T three_bit_struct;
    unsigned char another_three_bits : 3;
}weird_union_T;


typedef struct
{
    weird_union_T problem_union; 
    unsigned char another_bit : 1;
    unsigned char reserved : 4;
}my_structure_T;


int _tmain(int argc, _TCHAR* argv[])
{
     int size;

     size = sizeof(my_structure_T);

     return 0;
}


#ifdef WIN32
#pragma pack(pop)
#endif
Run Code Online (Sandbox Code Playgroud)

Gra*_*and 6

问题是大小three_bit_struct_T将被四舍五入到最接近的字节*,而不管它在其位域中只包含三个位.结构简单地不能具有部分字节的大小.所以当你用额外的字段来增加它时my_structure_T,不可避免地会将大小溢出到第二个字节.

要将所有内容塞入单个字节,您必须将所有位域成员放在外部,my_structure_T而不是将它们作为内部结构/联合.

我认为你能做的最好的事情就是将整个事情作为一个联盟.

typedef struct
{
    unsigned char bit_a : 1;
    unsigned char bit_b : 1;
    unsigned char bit_c : 1;
    unsigned char another_bit : 1;
    unsigned char reserved : 4;
} three_bit_struct_T;

typedef struct
{
    unsigned char another_three_bits : 3;
    unsigned char another_bit : 1;
    unsigned char reserved : 4;
} another_three_bit_struct_T;

typedef union
{
    three_bit_struct_T three_bit_struct;
    another_three_bit_struct_T another_three_bit_struct;
} my_union_T;
Run Code Online (Sandbox Code Playgroud)

(*)或字,取决于对齐/包装设置.