DEV Community

Cover image for Bitwise Operations for CP (DSA - 1)
Madhav Ganesan
Madhav Ganesan

Posted on • Updated on

Bitwise Operations for CP (DSA - 1)

Bitwise operations are fundamental to many programming tasks and for competitive programming. This blog will cover the basic bitwise operations, including AND, OR, XOR, NOT, left shift, and right shift, with examples to illustrate their usage.

What are Bitwise Operations?

Bitwise operations directly manipulate the individual bits of binary representations of numbers.

Bitwise Operators in C++

1) Bitwise AND (&):

int main() {
    int a = 5;    // 0101
    int b = 3;    // 0011 
    int result = a & b;  // 0001 
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

2) Bitwise OR (|)

int main() {
    int a = 5;    // 0101
    int b = 3;    // 0011
    int result = a | b;  // 0111
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

3) Bitwise XOR (^)

int main() {
    int a = 5;    // 0101 
    int b = 3;    // 0011
    int result = a ^ b;  // 0110
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

4) Bitwise NOT (~)

int main() {
    int a = 5;    // 0101 
    int result = ~a;  // 1010
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

5) Left Shift (<<)
This is equivalent to multiplying the number with 2 (X2)

int main() {
    int a = 5;    // 0101 
    int result = a << 1;  // 1010
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

6) Right Shift (>>)
This is equivalent to dividing the number with 2 (/2)

int main() {
    int a = 5;    // 0101 
    int result = a >> 1;  // 0010
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Builtin Function:

In C++, bitset is a useful feature from the standard library that allows you to handle binary numbers more easily.

Initializing binary number:

bitset<8> bset1(32); 
bitset<8> bset2("10101");
Enter fullscreen mode Exit fullscreen mode

Accessing & Modifying bits:

bset1[0] = 1; // Sets the 0th bit to 1
bset1.set(1); // Sets the 1st bit to 1
bset1.reset(2); // Resets the 2nd bit to 0
bset1.flip(3); // Flips the 3rd bit
Enter fullscreen mode Exit fullscreen mode

Checking set bits:

if (bset1.test(1)) {
   cout << "The 1st bit is set." << endl;
}
Enter fullscreen mode Exit fullscreen mode

Counting set bits:

bset1.count() // Returns the number of set bits
bset1.size() // Returns the total number of bits
Enter fullscreen mode Exit fullscreen mode

Converting to different formats:

bset1.to_ulong(); // Converts to unsigned long
bset1.to_string(); // Converts to string
Enter fullscreen mode Exit fullscreen mode

Feel free to reach out if you have any questions or need further assistance. 😊📁✨

Top comments (0)