Invalid attributes using bit fields in C ++ class

I am trying to use bit fields in C ++ to achieve a specific class size, but for some reason it is larger than I expected.

The problem is that a class with 32 bits (4 bytes) reports (when passed as sizeof argument) 5 bytes. Example class below:

 typedef unsigned char u8; typedef unsigned int u32; class Test { u8 four_bit_field : 4; u8 eight_bit_field; u32 twenty_bit_field : 20; }__attribute__((packed)); 

If the four_bit_field and eight_bit_field switched, sizeof returns the correct size, 4 bytes. I believe this is probably a memory allocation problem.

So, does anyone know the reason for this behavior? And, most importantly, how can I fix this without switching any positions.

+6
source share
3 answers

Field u8 without counting bits is aligned with the next byte boundary, and is not filled with other bit fields. Thus, your first 4 bits take bytes, and the remaining 8 bits occupy bytes, and the last 20 bits occupy 3 bytes, a total of 5.

If you add a bitfield size to an 8-bit field, it will work, see http://ideone.com/Bexw6l

+10
source

This is indeed a leveling problem. u8 eight_bit_field not a bit field, it is a simple unsigned char (on behalf of), and char , signed char or unsigned char naturally aligned on the byte boundary.

So you end up with 4 fill bits between four_bit_field and eight_bit_field and 4 fill bits after twenty_bit_field ; the latter can be reused by the derived class; the former is permanently lost.

+2
source

Try setting alignment to 1 byte:

 #pragma pack(1) class Test { u8 four_bit_field : 4; u8 eight_bit_field : 8; u32 twenty_bit_field : 20; }; #pragma pack() 
+2
source

All Articles