简体   繁体   English

在 C 中跨匿名结构合并位字段

[英]merge bit fields across anonymous structs in C

I have the following code:我有以下代码:

typedef unsigned short u16;

struct S {
    struct {
        u16 a: 9;
        u16 b: 1;
        u16 c: 1;
        u16 d: 1;
    } __attribute__((packed));

    u16 e: 4;

} __attribute__((packed));

when I check sizeof(S) , it returns 3. is it possible to somehow instruct gcc to merge bitfields across anonymous structs so that sizeof(S) returns 2.当我检查sizeof(S)时,它返回 3。是否有可能以某种方式指示 gcc 跨匿名结构合并位域,以便sizeof(S)返回 2。

The result you are looking for can be obtained by making the structure union instead, with two bit-fields overlapping.您正在寻找的结果可以通过使结构union来获得,而不是两个位域重叠。 The bits "used" by the first bitfield will be marked as "reserved" in the second one:第一个位域“使用”的位将在第二个位域中标记为“保留”:

union S {
    struct {
        u16 a: 9;
        u16 b: 1;
        u16 c: 1;
        u16 d: 1;
    } ;
    
    struct {
        u16 reserved: 12; // Number of bits used in the first struct
        u16 e: 4;
    };
};

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM