WTF is bitwise ✨
$$$$ \begin{array}{|c|c|c|c|} \hline 2^x & \text{Value} & \text{Binary Form} & \text{Shift} \\ \hline 2^0 & 1 & 0001 & 1 \ll 0 \\ 2^1 & 2 & 0010 & 1 \ll 1 \\ 2^2 & 4 & 0100 & 1 \ll 2 \\ 2^3 & 8 & 1000 & 1 \ll 3 \\ 2^4 & 16 & 0001 0000 & 1 \ll 4 \\ 2^5 & 32 & 0010 0000 & 1 \ll 5 \\ 2^6 & 64 & 0100 0000 & 1 \ll 6 \\ \hline \end{array} $$
$$
Simple trick is : number of zeroes after 1 in binary form is equal to power of 2. For eg: if 2^3 = 8 then its binary form would be 1000(1 and 3 zeroes) and also 1 << 3.
if you want to multiply any 'n' number by 2, then n << 1
if you want to divide any 'n' number by 2, then n >> 1
if you want to multiply any 'n' number by 2^x, then n << x
if you want to divide any 'n' number by 2^x, then n >> x
Checking if a number is even or odd:
- An integer
n
is even if(n & 1) == 0
and odd if(n & 1) == 1
.
- An integer
Swapping two numbers without using a temporary variable:
a ^= b; b ^= a; a ^= b;
Setting a particular bit to 1:
- To set the
i
-th bit of a numbern
to 1:n |= (1 << i)
.
- To set the
Setting a particular bit to 0:
- To set the
i
-th bit of a numbern
to 0:n &= ~(1 << i)
.
- To set the
Toggling a particular bit:
- To toggle the
i
-th bit of a numbern
:n ^= (1 << i)
.
- To toggle the
Checking if a number is a power of two:
- A number is a power of two if
n & (n - 1) == 0
andn > 0
.
- A number is a power of two if
Counting set bits (number of 1s) in a binary representation:
int countSetBits(int n) { int count = 0; while (n) { n &= (n - 1); count++; } return count; }
Finding the rightmost set bit:
- To find the position of the rightmost set bit (least significant bit), you can use
n & -n
.
- To find the position of the rightmost set bit (least significant bit), you can use
Turning off the rightmost set bit:
- To turn off the rightmost set bit:
n &= (n - 1)
.
- To turn off the rightmost set bit:
Extracting the rightmost set bit:
- To extract the rightmost set bit:
rightmostBit = n & -n
.
- To extract the rightmost set bit:
Setting all bits in a number to 1:
- To set all bits in a number to 1:
n = (1 << numberOfBits) - 1
.
- To set all bits in a number to 1:
Subscribe to my newsletter
Read articles from Ashutosh Kumar (Ashu) directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by