I like to view a bit-field structure as a special case of of scalar:
a regular scalar with the added convenience of being able to 'address'
certain bits. Isn't this how bit-fields are used in hardware device
drivers (mapping certain registers)?
Some people write code like that. Others write code that survives
changing compilers.
In my case my input data is of type unsigned char which needs to be
mapped/assigned on/to a bit-field structure. Instead of writing out
all the nuts al bolts (with ... >> 4 & 0x3 ...) I want C to help me
out here and let the compiler do the work for me.
Unfortunately, as Dennis Ritchie himself once put it, C's bitfields
are "a botch and a blemish". For instance:
How is bit-field structure allignment specified in the C spec?
It is not.
Much worse, however, is the fact that two different compilers FOR THE
SAME MACHINE may reverse the order of the bits in some bitfield:
/* device connected to motorola 68010; C compiler has 16-bit int */
struct hardware_reg {
unsigned int go:1; /* set to 1 to make device run */
unsigned int cmd:3; /* command */
unsigned int ctl:4; /* control bits */
unsigned int dma:1; /* set to 1 to use DMA */
unsigned int :3; /* unused */
unsigned int status:4; /* device status */
unsigned int addr; /* DMA address */
};
Compiled with Compiler A, the "go" bit is (as desired) the high bit
of the first 16-bit word, but compiled with Compiler B, the "go" bit
becomes the *low* bit of that word.
Using "unsigned short csr, addr;" and defining bits for the control
and status register works on every compiler you will find for that
68010-based system (even those with 32-bit ints). C gives you (the
programmer) no control whatsoever of where the bits in the bitfield
wind up. If you want to write this sort of code, you might consider
Ada, which has the necessary construct (the "representation clause").