Bit Manipulation - All that you must know!
5713
IF YOU KNOW THE BASICS SKIP TO 8Th point!

1)Bitwise AND(&)
Returns bit values of 1 for positions where both
numbers had a one, and bit values of 0 where both numbers did not have one.

2)Bitwise OR(|)
returns bit values of 1 for positions where either bit
or both bits are one, the result of 0 only happens when both bits are 0.

3)Bitwise XOR(^)
returns bit values of 1 for positions
where both bits are different; if they are the same then the result is 0.

4)Bitwise Left-shift(<<)
The bitwise left shift moves all bits in the number to the left and fills vacated bit positions with 0.

5)Bitwise RIght-Shift(>>)
The bitwise right shift moves all bits in the number to the right.

NOTE: Where the left shift filled the vacated positions with 0, a right
shift will do the same only when the value is unsigned. If the value is signed then a right shift will fill the vacated bit positions with the sign bit or 0, whichever one is implementation-defined. So the best option is to never right shift signed value

6)Bitwise Complement(~)
The bitwise complement inverts the bits in a single binary number.

7)Checking Whether K-th Bit is Set or Not
n & (1 ≪ K -1). If the expression is true then we can say the Kth bit is set

8)Setting K-th Bit: n | 1 ≪ (K – 1)

9)Clearing K-th Bit : n & ~(1 ≪ K – 1)

10)Toggling K-th Bit : n ^(1 ≪ K – 1)

11)Toggling Rightmost One Bit : n & n – 1

12)Isolating Rightmost Zero Bit : ~n & n + 1

13)Checking Whether Number is Power of 2 or Not : if(n & n – 1 == 0)

14)Multiplying Number by Power of 2 :
to multiply the number with 2K we can use the expression: n ≪ K

15)Dividing Number by Power of 2 :
divide the number with 2K we can use the expression: n ≫ K

16)Performing Average without Division
We can use mid = (low + high) >> 1. Note that using (low + high) / 2 for midpoint calculations
won’t work correctly when integer overflow becomes an issue. We can use bit shifting and also
overcome a possible overflow issue: low + ((high – low)/ 2) and the bit shifting operation for
this is low + ((high – low) >> 1)

Comments (9)