296 Chapter 12 Operations on Bits
unsigned int f2:1;
unsigned int f1:1;
unsigned int :3;
};
to achieve the same representation on a machine that assigns fields from right to left as
depicted in Figure 12.1. Never make any assumptions about how structure members—
whether they contain bit field members or not—are stored.
You can also include normal data types within a structure that contains bit fields. So if
you want to define a structure that contained an int,a char, and two one-bit flags, the
following definition is valid:
struct table_entry
{
int count;
char c;
unsigned int f1:1;
unsigned int f2:1;
};
Certain points are worth mentioning with respect to bit fields.They can only be
declared to be of integer or _Booltype. If just intis used in the declaration, it’s imple-
mentation dependent whether this is interpreted as a signed or unsigned value.To play it
safe, use the explicit declarations signed intor unsigned int.A bit field cannot be
dimensioned; that is, you cannot have an array of fields, such as flag:1[5]. Finally, you
cannot take the address of a bit field, and, therefore, there is obviously no such thing as a
type “pointer to bit field.”
Bit fields are packed into unitsas they appear in the structure definition, where the
size of a unitis defined by the implementation and is most likely a word.
The C compiler does notrearrange the bit field definitions to try to optimize storage
space.
A final point concerning the specification of fields concerns the special case of an
unnamed field of length 0.This can be used to force alignment of the next field in the
structure at the start of a unit boundary.
This concludes the discussion of bit operations in C.You can see how much power
and flexibility the C language provides for the efficient manipulation of bits. Operators
are conveniently provided in the language for performing bitwise AND, Inclusive-OR,
Exclusive-OR, ones complement, and left and right shift operations. A special bit field
format enables you to allocate a specified number of bits for a data item and to easily set
and retrieve its value without having to use masking and shifting.
See Chapter 14, ”More on Data Types,” for a discussion on what happens when you
perform bitwise operations between two values of differing integral types, for example
between an unsigned long intand a short int.
Before proceeding to the next chapter, try the following exercises to test your under-
standing of bit operations in C.