c++ - Issues with C++ bitfields
问题描述
I have to write a file header with a specific data format. For simplicity, let's just assume it is:
- bits [0-7]: index a
- bits [8-9]: index b
- bits [10-15]: index c
All of them are simple unsigned integers. I thought I might use bit fields to get a nice syntax. I defined
struct Foo {
unsigned int a : 8, b : 2, c : 6;
};
However, I get sizeof(Foo) == 4
. Why is that so? I expected a 2-byte structure here. Is the compiler adding padding between my fields? If I use unsigned char
as my member type, I get a size of 2 bytes.
On cppreference, it says:
Multiple adjacent bit fields are usually packed together (although this behavior is implementation-defined).
Does that mean that I cannot rely on the fields being packed together? Eventually, I will use memcpy
to turn this struct
into a stream of bytes and write that to a file. Is that not a good use of bit fields? This will only work if these bits are guaranteed to be packed together.
EDIT: The actual header relates to the GIF format. Many indexes are packed into just a few bytes. Some of them are made up of 1, 2, 3 or more bits.
解决方案
来自[class.bit]/1 [extract]:
[...] 类对象内的位域分配是实现定义的。位域的对齐是实现定义的。
并且,来自[defns.impl.defined]:
实现定义的行为
行为,对于格式良好的程序构造和正确的数据,这取决于实现和每个实现文档
因此,对于可移植的实现,您不能依赖任何特定类型的行为来实现实现定义的行为。但是,如果您正在为特定平台和编译器进行开发,则可以在一定程度上依赖记录在案的实现定义的行为。
推荐阅读
- android - RecyclerView 没有填充,可能是一个愚蠢的适配器问题
- python - 导入请求不起作用 Python 3.7
- rust - 为 T 实现 From 特征,其中 T 实现 Display
- python - 如何找到包含多个单元格的列表的平均值?
- c++ - 单例:避免 GetIntance()
- ios - 找不到它有什么问题。错误域 = NSCocoaErrorDomain 代码 = 3840 “无值。” UserInfo={NSDebugDescription=无值。}
- python - 在具有匹配属性的 dict 数组中查找最小值,返回最大的分组
- python - AWS Lambda - S3 put_object 参数正文的类型无效
- python - 没有 .sorted 的第二大整数
- python - 获取包含字典的 2 个列表之间的差异