简体   繁体   中英

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.

From [class.bit]/1 [extract]:

[...] Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined.

and, from [defns.impl.defined] :

implementation-defined behavior

behavior, for a well-formed program construct and correct data, that depends on the implementation and that each implementation documents

Thus, for a portable implementation you cannot rely on any specific kind of behaviour for implementation-defined behaviour. If you are developing for a particular platform and compiler, however, you could rely on documented implementation-defined behaviour to a certain extent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM