C++ - Defining 1 Bit Bools
C++ - Defining 1 Bit Bools
这样定义结构体的结果是什么?
typedef struct {
bool Bit0 : 1; //Bit 0
bool Bit1 : 1;
bool Bit2 : 1;
bool Bit3 : 1;
bool Bit4 : 1;
bool Bit5 : 1;
bool Bit6 : 1;
bool Bit7 : 1; //Bit 7
char SomeOtherData;
}Char16Bits;
...
Char16Bits MyStructure;
MyStructure.Bit0 = true;
MyStructure.Bit1 = false;
在我的测试程序中,一切似乎都很好,每个"Bit0-7"只占用1位,我可以看到它们在内存中按预期工作。"SomeOtherData"字符似乎是在查看VS2010内存窗口时内存结构的第二个字节,这一切都很好。
然而,我能可靠地假设这些位总是只占用1位吗?如果我记忆2个字节到这个结构中,第二个字节是否总是可靠地占据我的结构中的"SomeOtherData"字符元素?
结构打包总是与编译器相关,但大多数编译器应该将其放在两个字节内。
可以依赖sizeof(MyStructure)
作为数据结构的总大小(考虑到此处讨论的填充,为什么结构的n't sizeof等于每个成员的sizeof的总和?),offsetof(Char16Bits,SomeOtherData)
是SomeOtherData
的正确偏移量。
如果您需要编写假设特定大小或偏移量的代码,请使用assert()
或static_assert()
,以便代码不允许在不遵循您的假设的平台上运行。
相关文章:
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- WinAPI IcmpSendEcho on 64-bit platform
- 将硬盘驱动器上的 BIT XXX 从 0 更改为 1
- 如何使用'bit-blast'方法以命题逻辑形式打印给定的公式?
- 仅在测试中"dlopen failed: is 32-bit instead of 64-bit"
- 如何将Bools中的一个元素设置为true
- 将枚举类型保存在位字段 [dcl.enum] [class.bit] 中
- AES CBC 128 bit encryption -OpenSSL
- 在字节中访问struct或BIT的子集更快
- 将"8 bit"(字节)字符串写入二进制文件?
- 使用config.json文件与BBC Micro:BIT MED在线编译器
- CMake 64-bit with SFML 64-bit
- P1236R1:为什么 c++ 标准在定义整数时试图摆脱单词"bit"?
- 在C++/Visual Studio中,通过给定数据格式(doubles、float、int、1位bools)的UDP发
- boost 1.69 visual studio 2017 64-bit
- 32 bit PPC rlwinm instruction
- 解释"Bit String"的最佳方式是什么
- 它是如何工作的"checking bit flag"
- std :: getline部分读取第一行,并设置eof-bit
- C++ - Defining 1 Bit Bools