Question

I'm trying to use bit-fields in C++ to achieve a specific class size, but for some reason it's bigger than I expected.

The problem is, a class with 32 bits (4 bytes) is reporting (when passed as argument to sizeof) 5 bytes. Example class bellow:

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 positions are switched, sizeof return the proper size, 4 bytes. I believe that it's problably a memory allignment problem.

So, someone knows the reason behind this behaviour? And, most importantly, how can I fix this, without switching any positions.

Was it helpful?

Solution

The u8 field without a bit count is being aligned to the next byte boundary, rather than being packed with the other bit fields. Thus your first 4 bits take a byte, the second 8 bits take a byte, and the last 20 bits take 3 bytes, totaling 5.

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

OTHER TIPS

It is, indeed, a problem of alignment. u8 eight_bit_field is not a bitfield, it's a plain unsigned char (from the name), and a char, signed char or unsigned char is naturally aligned on a byte boundary.

You therefore end up with 4 bits of padding between four_bit_field and eight_bit_field and 4 bits of padding after twenty_bit_field; the latter possibly reusable by a derived class, the former forever lost.

Try forcing the 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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top