Why manipulate bits?
When working with embedded devices each bit of an integer can be important to keep track of. Specially when reading and writing to hardware registers sometimes simply flipping a single incorrectly set bit can be the solution to hours of unexpected bahaviour and troubleshooting.
Bitwise operators
int main()
{
int a = 0x01;
int b = 0x02;
int c = 0x03;
return 0;
}
Setting a bit
The following code sets the 3rd
bit in integer n high.
Inititally When n is printed it will print 1 based on its declaration but the second time it will evaluate to a value of 9
after the bit manipulation.
int n = 0b00000001;
printf("$d\n", n); // outputs 1
n |= (0b1) << 3; // changed to 0b00001001
printf("$d\n", n); // outputs 9
Clearing a bit
int main()
{
int a = 0x01;
int b = 0x02;
int c = 0x03;
return 0;
}
Bitmasking
using namespace std;
int main()
{
int mask = 0x0FF;
return 0;
}
Practice
To further test your understanding use the following leetcode challenges