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.

  1. if you want to multiply any 'n' number by 2, then n << 1

  2. if you want to divide any 'n' number by 2, then n >> 1

  3. if you want to multiply any 'n' number by 2^x, then n << x

  4. if you want to divide any 'n' number by 2^x, then n >> x

  5. Checking if a number is even or odd:

    • An integer n is even if (n & 1) == 0 and odd if (n & 1) == 1.
  6. Swapping two numbers without using a temporary variable:

    •   a ^= b;
        b ^= a;
        a ^= b;
      
  7. Setting a particular bit to 1:

    • To set the i-th bit of a number n to 1: n |= (1 << i).
  8. Setting a particular bit to 0:

    • To set the i-th bit of a number n to 0: n &= ~(1 << i).
  9. Toggling a particular bit:

    • To toggle the i-th bit of a number n: n ^= (1 << i).
  10. Checking if a number is a power of two:

    • A number is a power of two if n & (n - 1) == 0 and n > 0.
  11. 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;
        }
      
  12. Finding the rightmost set bit:

    • To find the position of the rightmost set bit (least significant bit), you can use n & -n.
  13. Turning off the rightmost set bit:

    • To turn off the rightmost set bit: n &= (n - 1).
  14. Extracting the rightmost set bit:

    • To extract the rightmost set bit: rightmostBit = n & -n.
  15. Setting all bits in a number to 1:

    • To set all bits in a number to 1: n = (1 << numberOfBits) - 1.
0
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

Ashutosh Kumar (Ashu)
Ashutosh Kumar (Ashu)