我有以下代码:
struct Foo {
uint16_t a:5;
uint16_t b:5;
uint16_t c:5;
};
uint16_t bits = 0xdae;
const Foo& foo = *reinterpret_cast<const Foo*>(&bits);
printf("%x %x %x\n", foo.a, foo.b, foo.c);
输出是我在纸上计算时所期望的:
e d 3
如果我使用 uint32_t 而不是 uint16_t 位域,我会得到相同的结果。
但是当我使用 uint8_t 位域而不是 uint16_t 时,我得到的结果不一致:
e d 6
或
e d 16
两者都不正确。为什么将 uint8_t 用于位域会导致这种奇怪的行为?
最佳答案
编译器可能会在结构成员之间添加填充(或者可能不会,由其自行决定),当您只是尝试将整个结构作为一堆位访问时,您不会考虑到这一点。基本上你不能这样做(行为是未定义的,你的代码只是错误的)。您需要按名称访问结构成员或使用编译器特定的扩展来控制布局/填充。
关于c++ - C/C++ : uint8_t bitfields behave incorrectly and inconsistently,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44444222/