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.
source share