Next: Exercises
Up: Low Level Operators
Previous: Bitwise Operators
Bit Fields allow the packing of data in a structure. This is especially
useful when memory or data storage is at a premium. Typical examples:
- Packing several objects into a machine word. e.g. 1 bit flags can be
compacted - Symbol tables in compilers.
- Reading external file formats - non-standard file formats could be read
in. E.g. 9 bit integers.
C lets us do this in a structure definition by putting :bit length
after the variable. i.e.
Here the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4 bit type and a 9 bit funny_int.
C automatically packs the above bit fields together.
Access members as usual via:
pack.type = 7;
NOTE:
- Only lower bits will be assigned to an bit number. So type
cannot take values larger than 15 (4 bits long).
- Bit fields are always converted to integer type for
computation.
- You are allowed to mix ``normal'' types with bit fields.
- The unsigned definition is important - ensures that no bits are used
as a flag.