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.
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
extern uint8_t value;
value |= 1 << x; |
Note: Using the |= assignment operator
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
value |= 1 << x; |
is essentially the same as doing
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
value = value | (1 << x); |
Example
Suppose we have the following value
...
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
0b00000100 | 0b00000001 = 0b00000101 |
Clearing a Bit
The bitwise AND operator can be used to clear a bit. The following code snippet clears bit x:
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
extern uint8_t value;
value &= ~(1 << x); |
Note: Using the &= assignment operator
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
value &= ~(1 << x); |
is essentially the same as doing
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
value = value & ~(1 << x); |
Example
Suppose we have the following value
...
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
0b00000111 & 0b11111101 = 0b00000101 |
Toggling a Bit
The XOR operator allows you to toggle a bit. The following code snippet toggles bit x.
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
extern uint8_t value;
value ^= 1 << x; |
Note: Using the ^= assignment operator
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
value ^= 1 << x; |
is essentially the same as doing
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
value = value ^ (1 << x); |
Example
Suppose we have the following value
...
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
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.
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
extern uint8_t value;
bit = (value >> x) & 1; |
Example
Suppose we have the following value
...
Code Block |
---|
language | cpp |
---|
theme | Confluence |
---|
|
(0b00010111 >> 2) = 0b000000010b00000101 |
Then, the AND operator is applied
...