我可以引用C位域的另一部分吗?

gab*_*ton 4 c bit-manipulation bit

我试图提出一个代码片段,其中结构的一个属性引用同一结构的另一个属性中的特定位。这看起来像:

struct A {
    unsigned char type;
    unsigned char is_family_a : 1;  // should reference bit 7 of above somehow
};

struct A example;
example.type = 0x17;
printf("%i\n", example.is_family_a);  // 0
example.type = 0xF7;
printf("%i\n", example.is_family_a);  // 1
Run Code Online (Sandbox Code Playgroud)

我查看了cppreference页面,却什么也没看到。我也环顾了stackoverflow,但并未真正找到任何东西。如果使用宏,这似乎确实可行,但我认为编译器可能比我能更好地优化这类事情。

R..*_*R.. 5

应该这样做:

struct A {
    union {
        unsigned char type;
        struct {
            unsigned char : 7;  // remove for big endian
            unsigned char is_family_a : 1;  // should reference bit 7 of above somehow
        };
    };
};
Run Code Online (Sandbox Code Playgroud)