gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:28:09 24 4
gpt4 key购买 nike

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

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,但没有真正找到任何东西。如果我使用宏,这似乎确实有效,但我认为编译器可能比我能更好地优化这类事情。

最佳答案

应该这样做:

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

关于我可以引用 C 位域的另一部分吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56822723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com