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 char
s and manipulate them programmatically to be assured of portability?
The relevant quote I could find is 6.7.2.1(1), from C99:
An implementation may allocate any addressable storage unit large enough to hold a bit- field. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified.
I think that the unsigned
isn't actually the "underlying unit" type, but rather, it's only a part of the bitfield declaration itself: T : n
means "take n bits of type T
". 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 a char
; one for v1
, one for v2
, and the last one for v3, 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).