Clearing, Toggling, Setting, and Checking a Bit
Understanding these three operations will make your life much easier.
Setting a Bit
The bitwise OR operator is used to set a bit. The following code snippet sets bit x.
extern uint8_t value; value |= 1 << x;
Note: Using the |= assignment operator
value |= 1 << x;
is essentially the same as doing
value = value | (1 << x);
Example
Suppose we have the following value
uint8_t value = 0x04;
which has the following 8-bit binary representation
0b00000100
and we want to set bit 0.
Then, we can do the following
value |= 1 << 0;
which results in
0b00000100 | 0b00000001 = 0b00000101
Clearing a Bit
The bitwise AND operator can be used to clear a bit. The following code snippet clears bit x:
extern uint8_t value; value &= ~(1 << x);
Note: Using the &= assignment operator
value &= ~(1 << x);
is essentially the same as doing
value = value & ~(1 << x);
Example
Suppose we have the following value
uint8_t value = 0x07;
which has the following 8-bit binary representation
0b00000111
and we want to clear bit 1. Then, we can do the following
value &= ~(1 << 1);
The
~
operator is the NOT operator, which flips all the set and unset bits, such that any set bits will be unset, and vice versa.
So every other bit is set, except for the desired bit at position x.
~(1 << 1) = 0b11111101
Now, when we AND it to the value, what happens is any bits that are both set will remain set, and any bits that weren't set will remain unset. In addition, for bit x, if it was originally set, it will be ANDed with 0 (and if it wasn't set, it remains unset).
0b00000111 & 0b11111101 = 0b00000101
Toggling a Bit
The XOR operator allows you to toggle a bit. The following code snippet toggles bit x.
extern uint8_t value; value ^= 1 << x;
Note: Using the ^= assignment operator
value ^= 1 << x;
is essentially the same as doing
value = value ^ (1 << x);
Example
Suppose we have the following value
uint8_t value = 0x02;
which has the following 8-bit binary representation
0b00000010
and we want to toggle bit 1. Then, we can do the following
value ^= 1 << 1;
Essentially, we have
0b00000010 ^ 0b00000010 = 0b00000000
If we perform the same operation again
value ^= 1 << 1;
bit 1 is set again
0b00000000 ^ 0b00000010 = 0b00000010
Checking a Bit
To check a bit, you can combine the right shift and AND operators. The following code snippet checks bit x.
extern uint8_t value; bit = (value >> x) & 1;
Example
Suppose we have the following value
uint8_t value = 0x17;
which has the following 8-bit binary representation
0b00010111
and we want to check if bit 2 is set. Then, we can do the following
bit = (value >> 2) & 1;
Essentially, we've first shifted the value x places to the right
(0b00010111 >> 2) = 0b00000101
Then, the AND operator is applied
0b00000101 & 0b00000001 = 0b00000001