首页 > 解决方案 > Issues with C++ bitfields

问题描述

I have to write a file header with a specific data format. For simplicity, let's just assume it is:

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.

标签: c++bit-fields

解决方案


来自[class.bit]/1 [extract]:

[...] 类对象内的位域分配是实现定义的。位域的对齐是实现定义的。

并且,来自[defns.impl.defined]

实现定义的行为

行为,对于格式良好的程序构造和正确的数据,这取决于实现每个实现文档

因此,对于可移植的实现,您不能依赖任何特定类型的行为来实现实现定义的行为。但是,如果您正在为特定平台和编译器进行开发,则可以在一定程度上依赖记录在案的实现定义的行为。


推荐阅读