Skip to content

Instantly share code, notes, and snippets.

@arsperger
Created November 1, 2021 06:11
Show Gist options
  • Save arsperger/76ad993fa41f2988da151ec59e6bc9b3 to your computer and use it in GitHub Desktop.
Save arsperger/76ad993fa41f2988da151ec59e6bc9b3 to your computer and use it in GitHub Desktop.
Let suppose few things first
num = 55 Integer to perform bitwise operations (set, get, clear, toggle).
n = 4 0 based bit position to perform bitwise operations.
How to get a bit?
To get the nth bit of num right shift num, n times. Then perform bitwise AND & with 1.
bit = (num >> n) & 1;
How it works?
0011 0111 (55 in decimal)
>> 4 (right shift 4 times)
-----------------
0000 0011
& 0000 0001 (1 in decimal)
-----------------
=> 0000 0001 (final result)
How to set a bit?
To set a particular bit of number. Left shift 1 n times. Then perform bitwise OR | operation with num.
num |= (1 << n); // Equivalent to; num = (1 << n) | num;
How it works?
0000 0001 (1 in decimal)
<< 4 (left shift 4 times)
-----------------
0001 0000
| 0011 0111 (55 in decimal)
-----------------
=> 0001 0000 (final result)
How to clear a bit?
Left shift 1, n times i.e. 1 << n.
Perform bitwise complement with the above result. So that the nth bit becomes unset and rest of bit becomes set i.e. ~ (1 << n).
Finally, perform bitwise AND & operation with the above result and num. The above three steps together can be written as num & (~ (1 << n));
Steps to clear a bit
num &= (~(1 << n)); // Equivalent to; num = num & (~(1 << n));
How it works?
0000 0001 (1 in decimal)
<< 4 (left shift 4 times)
-----------------
~ 0001 0000
-----------------
1110 1111
& 0011 0111 (55 in decimal)
-----------------
=> 0010 0111 (final result)
How to toggle a bit?
To toggle a bit we use bitwise XOR ^ operator. Bitwise XOR operator evaluates to 1 if corresponding bit of both operands are different, otherwise evaluates to 0.
Which means to toggle a bit, we need to perform XOR operation with the bit you want to toggle and 1.
num ^= (1 << n); // Equivalent to; num = num ^ (1 << n);
How it works?
If the bit to toggle is 0 then, 0 ^ 1 => 1.
If the bit to toggle is 1 then, 1 ^ 1 => 0.
0000 0001 (1 in decimal)
<< 4 (left shift 4 times)
-----------------
0001 0000
^ 0011 0111 (55 in decimal)
-----------------
=> 0010 0111 (final result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment