Bit Operations and Manipulation in C++ for Competitive Programming

Introduction

Basic Bitwise Operators

  1. AND (&)
  2. OR (|)
  3. XOR (^)
  4. NOT (~)
  5. Left Shift (<<)
  6. Right Shift (>>)

Common Bit Manipulation Techniques

  1. Check if a number is odd or even

    bool isOdd(int x) {
        return x & 1;
    }
    
    
  2. Get the i-th bit

    bool getBit(int x, int i) {
        return (x & (1 << i)) != 0;
    }
    
    
  3. Set the i-th bit

    void setBit(int &x, int i) {
        x |= (1 << i);
    }
    
    
  4. Clear the i-th bit

    void clearBit(int &x, int i) {
        x &= ~(1 << i);
    }
    
    
  5. Toggle the i-th bit

    void toggleBit(int &x, int i) {
        x ^= (1 << i);
    }
    
    
  6. Count the number of set bits (Hamming Weight)

    int countSetBits(int x) {
        int count = 0;
        while (x) {
            count += x & 1;
            x >>= 1;
        }
        return count;
    }
    
    

Advanced Bit Manipulation Techniques

  1. Check if a number is a power of 2

    bool isPowerOfTwo(int x) {
        return x && !(x & (x - 1));
    }