Writing programs for embedded systems often requires the manipulation of individual bits. Below is a list of the most common operations. In the examples we are performing them on an unsigned long variable called ctrl_reg.

Setting a bit

We can set a bit using the bitwise OR operator (|):

ctrl_reg |= 1UL << n;

The code above will set to 1 the bit in position n.

Clearing a bit

We can clear a bit using the bitwise AND operator (&) :

ctrl_reg &= ~(1UL << n);

The code above will clear bit n.  We first invert the bits with the bitwise NOT operator (~) and then perform the AND operation.

Toggling a bit

We can use the XOR operator (^)  to toggle a bit.

ctrl_reg ^= 1UL << n;

The code above will toggle bit n.

Getting the value of a bit

We can get the value of a particular bit by shifting and then using bitwise AND operation:

bit_value = (ctrl_reg >> n) & 1UL;

That will put the value of bit n into the variable bit_value.

Was this article helpful?