c++ - C/C++ : uint8_t bitfields behave incorrectly and inconsistently

标签 c++

我有以下代码:

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/

相关文章:

c++ - "Holder"存储不同对象类型的模板类。带参数和不带参数的构造函数

c++ - setText 方法替换现有文本,追加方法在新行之后输入新文本;我如何将 QString 背靠背连接起来?

c++ - QT OpenGL 链接错误

Android NDK 链接 OpenSSL

c++ - gcc 和 MSFT CL 之间的位域结构大小不同

c++ - MSI 安装的数据持久化

c++ - 无法将 'wchar_t' 转换为 'LPCSTR'

C++ 将指针传递给非静态成员函数

c++ - 具有不同签名的 std::function vector

c++ - 什么时候不是 constexpr 实际上是 constexpr