Short Note on Bit Manipulation

Last Updated : 24 Feb, 2026

Bit manipulation is the technique of performing operations directly on the binary representation of integers. Since computers store data in binary form (0 or 1 ), bitwise operations are extremely fast and memory-efficient.
The technique is widely used to perform binary operations efficiently, such as checking whether a number is odd or even, testing if a number is a power of two etc.

Common Bitwise Operators :

I. Bitwise And Operator ( &)

  • Sets each bit to 1 if both bits are 1 .
  • Some common uses are to check if a number is even or odd, ith bit is set or not etc.

Example - 5 & 3 → (00101)2 & (00011)2 → (00001)2 → 1

II. Bitwise OR Operator ( | )

  • Sets each bit to 1 if at least one bits are 1.
  • It is mainly used to set specific bits without affecting the others.

Example - 5 | 3 → (00101)2 | (00011)2 → (00111)2 → 7

III. Bitwise XOR Operator ( ^ )

  • Sets a bit to 1 if the corresponding bits are different.
  • It is widely used for finding unique elements, swapping two numbers without extra space etc.

Example - 5 ^ 3 → (00101)2 ^ (00011)2 → (00110)2 → 6

IV. Bitwise NOT Operator ( ~ )

  • Flips all the bits of a number, converting 1s to 0s and 0s to 1s.
  • It is useful when we need the complement of a number or while clearing bits using masks.
truth_table_of_bitwise_not_operator

Example - ~5 → ~ (00...00101)2 → (11...11010)2

V. Left Shift Operator ( << )

  • Shift a bit to left , adds 0s to its right.
  • Equivalent to multiply by 2 .
  • It is often used for fast multiplication by powers of two.

Example - (21 << 1)→ ( (10101)2 << 1) → (01010)2 → 10

logical_left_shift


VI. Right Shift Operator ( >> )

  • Shift bits to the right.
  • Equivalent to dividing by 2 .
  • It is used for fast division by powers of two.

Example - (21 >> 1)→ ( (10101)2 >> 1) → (01010)2 → 10

logical_right_shift

Built-in Bit Functions :

Basic Practice Problems on Bitwise Algorithm :

Note: All the Bitwise Practice Problems are optimized and run in O(1) Time Complexity with O(1) Auxiliary Space.

I. Set the i-th Bit in an Integer

  • First, we left shift 1 to i-th position via ( 1<<n ).
  • Then, use the "OR" operator to set the bit at that position.
C++
#include <iostream>
using namespace std;

// to set the ith bit
void Set(int& num, int pos)
{
    // First step is shift '1',
    // then perform bitwise OR
    num |= (1 << pos);
}
int main()
{
    int num = 4, pos = 1;
    Set(num, pos);
    cout << num << endl;
    return 0;
}
Java
class GfG {

    // to set the ith bit
    static void setBit(int[] num, int pos) {
        // First step is shift '1',
        // then perform bitwise OR
        num[0] |= (1 << pos);
    }

    public static void main(String[] args) {
        int[] num = {4};
        int pos = 1;

        setBit(num, pos);
        System.out.println(num[0]);
    }
}
Python
# to set the ith bit
def set_bit(num, pos):
    # First step is shift '1',
    # then perform bitwise OR
    num |= (1 << pos)
    return num

if __name__=="__main__":
    num = 4
    pos = 1
    
    num = set_bit(num, pos)
    print(num)
C#
using System;

class GfG
{
    // to set the ith bit
    static void Set(ref int num, int pos)
    {
        // First step is shift '1',
        // then perform bitwise OR
        num |= (1 << pos);
    }

    static void Main()
    {
        int num = 4, pos = 1;
        Set(ref num, pos);
        Console.WriteLine(num);
    }
}
JavaScript
// to set the ith bit
function setBit(num, pos) {
    // First step is shift '1',
    // then perform bitwise OR
    num |= (1 << pos);
    return num;
}

// Driver code
let num = 4;
let pos = 1;

num = setBit(num, pos);
console.log(num);

II. Unset/Clear the i-th Bit in an Integer

  • Left shift 1 by n positions using (1 << n) to create a mask with a 1 at the i-th bit.
  • Apply bitwise NOT ( ~ ) to the mask to make the nth bit 0 and all other bits 1.
  • Perform bitwise AND num & mask.
  • Since AND with 0 clears the bit and AND with 1 keeps it unchanged, the nth bit of num gets unset (cleared).
C++
#include <iostream>
using namespace std;

void unset(int& num, int pos)
{
    // perform operations
    int tem=(1<<pos);
    tem=~tem;
    num=num&tem;
}
int main()
{
    int num = 7;
    int pos = 1;
    unset(num, pos);
    cout << num << endl;
    return 0;
}
Java
class GfG {

    static void unsetBit(int[] num, int pos) {
        // perform operations
        int temp = (1 << pos);
        temp = ~temp;
        num[0] = num[0] & temp;
    }

    public static void main(String[] args) {
        int[] num = {7};
        int pos = 1;

        unsetBit(num, pos);
        System.out.println(num[0]);
    }
}
Python
def unset_bit(num, pos):
    # perform operations
    temp = (1 << pos)
    temp = ~temp
    num = num & temp
    return num

if __name__ == "__main__":
    num = 7
    pos = 1
    
    num = unset_bit(num, pos)
    print(num)
C#
using System;

class GfG
{
    static void Unset(ref int num, int pos)
    {
        // perform operations
        int temp = (1 << pos);
        temp = ~temp;
        num = num & temp;
    }

    static void Main()
    {
        int num = 7;
        int pos = 1;

        Unset(ref num, pos);
        Console.WriteLine(num);
    }
}
JavaScript
function unsetBit(num, pos) {
    // perform operations
    let temp = (1 << pos);
    temp = ~temp;
    num = num & temp;
    return num;
}

// Driver code
let num = 7;
let pos = 1;

num = unsetBit(num, pos);
console.log(num);

III. Toggling the i-th Bit of an Integer

  • Left shift 1 by n positions using (1 << n) to create a mask with a 1 at the i-th bit.
  • Then take the Xor ( ^) with of the mask with the number.
C++
#include <iostream>
using namespace std;

void toggle(int& num, int i) { 
    
    int mask = (1 << i);
    
    // toggle the ith bit
    num ^= mask; 
    
}

int main()
{
    int num = 4;
    int i = 1;
    toggle(num, i);
    cout << num << endl;
    return 0;
}
Java
public class GfG {

    static void toggle(int[] num, int i) {
        int mask = (1 << i);
        
        
       // toggle the ith bit
        num[0] ^= mask;   
    }

    public static void main(String[] args) {
        int[] num = {4};  
        int i = 1;
        toggle(num, i);
        System.out.println(num[0]);
    }
}
Python
def toggle(num, i):
    mask = (1 << i)
    
    
    # toggle the ith bit
    num ^= mask
    return num

if __name__ == "__main__":
    num = 4
    i = 1
    num = toggle(num, i)
    print(num)
C#
using System;

class GfG
{
    static void Toggle(ref int num, int i)
   {
        int mask = (1 << i);
        
        
        // toggle the ith bit
        num ^= mask;
    }

    static void Main()
    {
        int num = 4;
        int i = 1;
        Toggle(ref num, i);
        Console.WriteLine(num);
    }
}
JavaScript
function toggle(num, i) {
    let mask = (1 << i);
    
    
    // toggle the ith bit
    num ^= mask;
    return num;
}

// Driver code
let num = 4;
let i = 1;
num = toggle(num, i);
console.log(num);

IV. Count Set Bits in an Integer

  • You can use a built-in function or iterate through a loop to count the number of bits.
C++
#include <iostream>
using namespace std;

// calculate the number of set bits
int countBits(int n)
{
    int count = 0;
    while (n)
    {
        count += (n & 1);
        n >>= 1;
    }
    return count;
}

int main()
{
    int n = 5;
    cout << countBits(n) << endl;
    return 0;
}
Java
public class GfG {

    // calculate the number of set bits
    public static int countBits(int n) {
        int count = 0;
        while (n > 0) {
            count += (n & 1);
            n >>= 1;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(countBits(5)); 
    }
}
Python
# calculate the number of set bits
def countBits(n):
    count = 0
    while n:
        count += (n & 1)
        n >>= 1
    return count

if __name__ == "__main__":
    print(countBits(5))
C#
using System;
public class GfG
{
    // Function to calculate the number of set bits
    public static int countBits(int n)
    {
        int count = 0;
        while (n > 0)
        {
            count += (n & 1);
            n >>= 1;
        }
        return count;
    }

    static public void Main()
    {
        Console.WriteLine(countBits(5)); // Output: 2
    }
}
JavaScript
// calculate the number of set bits
function countBits(n) {
  let count = 0;
  while (n > 0) {
    count += (n & 1);
    n >>= 1;
  }
  return count;
}

// Driver code
console.log(countBits(5));

V. Check if a Number is Power of 2 or Not

  • If N is a power of 2, then N & (N−1) =0
  • This condition is also true for N=0.
  • Final check: n && !( n & ( n-1 ));
C++
#include<iostream>
using namespace std;

// check if x is power of 2
bool isPowerOfTwo(int x)
{
    
    return x && (!(x & (x - 1)));
}

int main ()
{
    cout<<isPowerOfTwo(2);
    return 0;
}
Java
public class GfG {

    // check if x is power of 2
    public static boolean isPowerOfTwo(int x) {
        return x != 0 && ((x & (x - 1)) == 0);
    }

    public static void main(String[] args) {
        System.out.println(isPowerOfTwo(2));
    }
}
Python
# check if x is power of 2
def isPowerOfTwo(x):
    return x and (not (x & (x - 1)))

if __name__ == "__main__":
    print(isPowerOfTwo(2))
C#
using System;

public class GFG
{
    // check if x is power of 2
    static public bool isPowerOfTwo(int x)
    {
        return (x != 0) && ((x & (x - 1)) == 0);
    }

    static public void Main()
    {
        Console.WriteLine(isPowerOfTwo(2));
    }
}
JavaScript
// check if x is power of 2
function isPowerOfTwo(x)
{
   
    return x && (!(x & (x - 1)));
}

// Driver code
console.log(isPowerOfTwo(2));

Application of Bit Manipulation :

finding_unique_elements


Comment