Programming in C

(Barry) #1
Bit Fields 295

The structure packed_structis defined to contain six members.The first member is
not named.The :3specifies three unnamed bits.The second member, called f1, is also an
unsigned int.The :1that immediately follows the member name specifies that this
member is to be stored in one bit.The flags f2and f3are similarly defined as being a
single bit in length.The member typeis defined to occupy eight bits, whereas the mem-
ber indexis defined as being 18 bits long.
The C compiler automatically packs the preceding bit field definitions together.The
nice thing about this approach is that the fields of a variable defined to be of type
packed_structcan now be referenced in the same convenient way normal structure
members are referenced. So, if you declare a variable called packed_dataas follows:


struct packed_struct packed_data;


you could easily set the typefield of packed_datato 7 with the simple statement


packed_data.type = 7;


or you could set this field to the value of nwith the similar statement


packed_data.type = n;


In this last case, you need not worry about whether the value of nis too large to fit into
the typefield; only the low-order eight bits of nwill be assigned to packed_data.type.
Extraction of the value from a bit field is also automatically handled, so the statement


n = packed_data.type;


extracts the typefield from packed_data(automatically shifting it into the low-order
bits as required) and assigns it to n.
Bit fields can be used in normal expressions and are automatically converted to inte-
gers. So the statement


i = packed_data.index / 5 + 1;


is perfectly valid, as is


if ( packed_data.f2 )
...


which tests if flag f2is true or false. One thing worth noting about bit fields is that there
is no guarantee whether the fields are internally assigned from left to right or from right
to left.This should not present a problem unless you are dealing with data that was creat-
ed by a different program or by a different machine. In such cases, you must know how
the bit fields are assigned and make the declarations appropriately.You could have
defined the structure packed_structas


struct packed_struct
{
unsigned int index:18;
unsigned int type:8;
unsigned int f3:1;

Free download pdf