Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a bitfield, why are some bits empty in the middle?

Tags:

c

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

like image 883
user11658398 Avatar asked Jun 17 '19 10:06

user11658398


3 Answers

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.

like image 81
Deepstop Avatar answered Oct 03 '22 14:10

Deepstop


This is a very handy feature. Most of the hardware registers have so gaps of unused/reserved bits for example:

enter image description here

Unnamed bitfields save us from having fields with the reserved1, reserved2 , ... names

like image 33
0___________ Avatar answered Oct 03 '22 14:10

0___________


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.

like image 44
Lundin Avatar answered Oct 03 '22 15:10

Lundin