Programming in C

(Barry) #1
Bit Fields 293

that contain packed information. Just as a short intcan be used to conserve memory
space on some computers, so can you pack information into the bits of a byte or word if
you do not need to use the entire byte or word to represent the data. For example, flags
that are used for a Boolean true or false condition can be represented in a single bit on a
computer. Declaring a charvariable that will be used as a flag uses eight bits (one byte)
on most computers, and a _Boolvariable is likely to use eight bits as well. In addition, if
you need to store many flags inside a large table, the amount of memory that is wasted
could become significant.
Two methods are available in C that can be used to pack information together to
make better use of memory. One way is to simply represent the data inside a normal
int,for example, and then access the desired bits of the intusing the bit operators
described in the previous sections. Another way is to define a structure of packed infor-
mation using a C construct known as a bit field.
To illustrate how the first method can be used, suppose you want to pack five data
values into a word because you have to maintain a very large table of these values in
memory. Assume that three of these data values are flags, which you call f1,f2,and f3;
the fourth value is an integer called type, which ranges from 1 to 255 ;and the final
value is an integer called index, which ranges from 0 to 100,000.
Storing the values of the flags f1,f2,and f3only requires three bits of storage, one
bit for the true/false value of each flag. Storing the value of the integer type, which
ranges from 1 to 255 ,requires eight bits of storage. Finally, storing the value of the inte-
ger index, which can assume a value from 0 to 100,000,requires 18 bits.Therefore, the
total amount of storage needed to store the five data values,f1,f2,f3,type,and index,
is 29 bits.You could define an integer variable that could be used to contain all five of
these values, as in


unsigned int packed_data;


and could then arbitrarily assign specific bits or fieldsinside packed_datato be used to
store the five data values. One such assignment is depicted in Figure 12.1, which assumes
that the size of packed_datais 32 bits.


f1

0 0000 000000 00000000000000000 0

unused f2 f3 type index

000

Figure 12.1 Bit field assignments in packed_data.

Note that packed_datahas three unused bits.You can now apply the correct sequence
of bit operations to packed_datato set and retrieve values to and from the various fields
of the integer. For example, you can set the typefield of packed_datato 7 by shifting
the value 7 the appropriate number of places to the left and then ORing it into
packed_data:


packed_data |= 7 << 18;

Free download pdf