首页 > 解决方案 > 我可以有一点引用 C 位域的另一部分吗?

问题描述

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

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

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

标签: cbit-manipulationbit

解决方案


这应该这样做:

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
        };
    };
};

推荐阅读