Bitwise Operations for CP (DSA - 1)

Bitwise Operations for CP (DSA - 1)

Mastering Bitwise Operations for Competitive Programming

ยท

2 min read

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;
}

2) Bitwise OR (|)

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

3) Bitwise XOR (^)

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

4) Bitwise NOT (~)

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

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;
}

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;
}

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");

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

Checking set bits:

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

Counting set bits:

bset1.count() // Returns the number of set bits
bset1.size() // Returns the total number of bits

Converting to different formats:

bset1.to_ulong(); // Converts to unsigned long
bset1.to_string(); // Converts to string

Feel free to reach out if you have any questions or need further assistance. ๐Ÿ˜Š๐Ÿ“โœจ

ย