If I have 16 bits that represent 3 pairs of values, each 5 bits long, and one other 1 bit value, in exactly this order, is it safe to use a bitfield to describe this? Does ANSI C guarantee that the bits will be exactly in the order that I specify?
struct {
unsigned v1 : 5;
unsigned v2 : 5;
unsigned v3 : 5;
unsigned v4 : 1;
} test;
If not, is there any other data structure that I can use to represent this? Or should I just store two 8 bit chars and manipulate them programmatically to be assured of portability?
The relevant quote I could find is 6.7.2.1(1), from C99:
I think that the
unsignedisn’t actually the “underlying unit” type, but rather, it’s only a part of the bitfield declaration itself:T : nmeans “take n bits of typeT“. The real question is whether the implementation is required to pick a “large” unit. For example, it could use three bytes by making the unit achar; one forv1, one forv2, and the last one forv3, v4. Or it could make the unit a 16-bit integer, in which case it would be required to use only one single unit.As you noted, though, the ordering of the bit fields within the unit is unspecified. The atomic unit of data in C is an address, and bitfields don’t have addresses. It’s guaranteed that the address of struct members increases in order of their declaration, but you cannot make such a statement about bitfields (only about their underlying units).