Introduction to Bit Manipulation

Bit manipulation involves the direct manipulation of bits within binary representations of data. It is a fundamental technique in computer science and programming, often used for optimizing performance, reducing memory usage, and performing low-level operations. Here are some common bit manipulation techniques and operations:

Bitwise Operators:

  • Bitwise AND (&): Sets each bit to 1 if both bits are 1.
  • Bitwise OR (|): Sets each bit to 1 if one of the bits is 1.
  • Bitwise XOR (^): Sets each bit to 1 if only one of the bits is 1.
  • Bitwise NOT (~): Inverts all the bits.
  • Bitwise Left Shift (<<): Shifts bits to the left, adding zeros on the right.
  • Bitwise Right Shift (>>): Shifts bits to the right, discarding bits on the right.
  • Bitwise Unsigned Right Shift (>>>): Shifts bits to the right, filling with zeros on the left (used in some languages like JavaScript).

Common Bit Manipulation Techniques:

  1. Get Power of Two:

Let say x = 101 if we do left shift by 1 then x becomes 1010 simply it gets multiply by 2. Similarly if we do left shift of x by k , then x becomes x*2

1<<1 = 10 = 2
1<<2 = 100 = 2*2                                                                                   
1<<3 = 1000 = 2*2*2

hence 1<<n = 2^n

function getPowerOfTwo(n) {
   return  1 << n;
}