Motivation
When programming close to the hardware, you often need to manipulate bits and flags efficiently. Doing this with bitwise operators and macros can get messy:
Bit fields provide a cleaner way to work with bits and flags in C structures.
Syntax
- The
type
for thedeclarator
must beunsigned int
,signed int
, orint
. - The
width
must be less than or equal to the size of the underlyingtype
.
Improved readability
With bit fields, the code reads more like accessing normal struct members:
And it is obviously less error-prone.
Memory optimization
Bit fields also enable packing data efficiently into the smallest space needed. For example, if you write:
You will use at least 3 * sizeof(unsigned int)
or 12 bytes to represent three small flags, that should only need three bits.
So if you write:
This uses up the same space as one unsigned int
, which is 4 bytes.
Hardware registers
Besides, bit fields are commonly used to represent hardware registers. If a 32-bit system register has a meaning for each bit, you can define it like:
This maps cleanly to the hardware while abstracting away the nitty-gritty of bit shifts.
Note
Bit fields can also be used to store values larger than one bit, although flags are more common.