Consider the following bitfield which I implemented with union
union
{
char fullByte;
struct
{
unsigned int bit0: 1;
unsigned int bit1: 1;
unsigned int bit2: 1;
unsigned int bit3: 1;
unsigned int bit4: 1;
unsigned int bit5: 1;
unsigned int bit6: 1;
unsigned int bit7: 1;
} bitField;
struct
{
unsigned int : 1;
unsigned int bit1to6 : 6;
unsigned int : 1;
} bitField2;
} bitByte;
cout << sizeof(bitByte) << endl; //prints 4
cout << sizeof(bitByte.fullByte) << endl; //prints 1
cout << sizeof(bitByte.bitField) << endl; //prints 4
cout << sizeof(bitByte.bitField2) << endl; //prints 4
Why are the union and the structs both 4 bytes? I only defined 8 bits, shouldn't it be one byte? If a bit is 2 bytes by the definition of unsigned int
, shouldn't it be 16 bytes? It seems that either way of thinking doesn't work. Why is it 4 bytes?
Also, I notice that I cannot do sizeof(bitByte.bitField.bit0)
, what would be the size of that? I defined it to be one bit, but unsigned int
is 2 bytes by definition. How many bytes would bit0, bit1, etc be?