When you define a bitfield, you can leave some bits blank in the middle and assign members to specific bits. Why are some bits emptying in the middle?
struct product {
unsigned int code : 6; // product code : 6 bit
unsigned int : 10; // not use 10 bit
unsigned int color : 5; // product color : 5 bit
unsigned int : 5; // not use 5 bit
unsigned int size : 6; // product size : 3 bit
};
I don't know why I don't use the bit in the middle
The bitfields are structured to avoid crossing word and byte boundaries. The first two, 6 and 10 bits, add up to 16 bits, while the other three, 5 and 5 and 6, also add up to 16 bits. It could be very inefficient to have a bit field be part of 2 separate 16 bit words.
This is a very handy feature. Most of the hardware registers have so gaps of unused/reserved bits for example:
Unnamed bitfields save us from having fields with the reserved1
, reserved2
, ... names
It is an unnamed bit-field, basically used-defined bit padding. From C17 6.7.2.1:
A bit-field declaration with no declarator, but only a colon and a width, indicates an unnamed bit-field. As a special case, a bit-field structure member with a width of 0 indicates that no further bit-field is to be packed into the unit in which the previous bitfield, if any, was placed.
So I would guess it is used to get a certain memory layout, perhaps to correspond with a certain pre-defined hardware register or communication protocol.
But also please note that it isn't well-defined which bit that's the MSB, and that the compiler if free to add padding of its own, so this bit-field isn't portable between compilers or systems. It is best to avoid bit-fields entirely, for any purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With