Bit Fields And Bit Manipulation/Masking


A bit field is a software/firmware variable that stores many bits in a consecutive memory structure.

Bit masking is the process of “masking” (selecting) specific bits in a bit field (a multi-bit software/firmware variable), e.g. a 32-bit integer, or uint32_t) to manipulate, without modifying the value of any bits that where not selected.

Bit masking is thought-of as a low-level operation, and is normally only seen in languages such C and C++ (higher level languages may still use bit masking, but the code is likely to be abstracted away from the user). C and C++ bit masking usually makes extensive use of pre-processor macros.

Setting Bits

The bit-wise OR operation ( |) can be used to set bits in a variable to 1. The bits in the bit field which you wish to set to 1 are ORed with 1, while those you wish to leave unchanged are ORed with 0.

Clearing Bits

The bit-wise AND operation ( &) can be used to set bits in a variable to 0. The bits in the bitfield which you wish to clear are ANDed with 0, while those you wish to leave unchanged are ANDed with 1.

Creating A Multi-Bit Bit Mask

This following example uses a macro to perform the masking and setting of bits. A function could be used, but macros are generally more efficient due to the lack of a function call.

You can then use it as in the following:

Note that the above BIT_MASK and SET_BITS macros only work for variables up to MAX_BIT_FIELD_WIDTH_BITS wide!

Use In The Industry

Many microcontroller manufactures (e.g. Atmel), provide firmware libraries and example code which make extensive use of bitfield manipulation to modify the registers which control the hardware peripherals (e.g the register(s) which configures the baud rate, parity and num. stop bits for a UART).