C++ Bitwise Operators

Bitwise operators in C++ allow manipulation of individual bits of integers. They are often used in low-level programming, optimization, and mask operations. This tutorial provides separate examples for each operator and a combined program demonstrating all bitwise operations.

1. Bitwise AND (&)

Performs AND operation on each pair of corresponding bits.

C++
Example: Bitwise AND operator
#include <iostream>
using namespace std;

int main() {
    int a = 5, b = 3; // 5:0101, 3:0011
    cout << "a & b = " << (a & b) << endl; // Output: 1 (0001)
    return 0;
}

2. Bitwise OR (|)

Performs OR operation on each pair of corresponding bits.

C++
Example: Bitwise OR operator
#include <iostream>
using namespace std;

int main() {
    int a = 5, b = 3; // 5:0101, 3:0011
    cout << "a | b = " << (a | b) << endl; // Output: 7 (0111)
    return 0;
}

3. Bitwise XOR (^)

Performs XOR operation on each pair of corresponding bits.

C++
Example: Bitwise XOR operator
#include <iostream>
using namespace std;

int main() {
    int a = 5, b = 3; // 5:0101, 3:0011
    cout << "a ^ b = " << (a ^ b) << endl; // Output: 6 (0110)
    return 0;
}

4. Bitwise NOT (~)

Inverts all bits of the number.

C++
Example: Bitwise NOT operator
#include <iostream>
using namespace std;

int main() {
    int a = 5; // 5:0101
    cout << "~a = " << (~a) << endl; // Output: -6 (two's complement)
    return 0;
}

5. Left Shift (<<)

Shifts bits to the left by a specified number of positions, filling with 0 from the right.

C++
Example: Left shift operator
#include <iostream>
using namespace std;

int main() {
    int a = 5; // 5:0101
    cout << "a << 1 = " << (a << 1) << endl; // Output: 10 (1010)
    return 0;
}

6. Right Shift (>>)

Shifts bits to the right by a specified number of positions. Leftmost bits filled with 0 (for unsigned) or sign bit (for signed).

C++
Example: Right shift operator
#include <iostream>
using namespace std;

int main() {
    int a = 20; // 20:00010100
    cout << "a >> 2 = " << (a >> 2) << endl; // Output: 5 (00000101)
    return 0;
}

7. Combined Program

This program demonstrates all bitwise operators together.

C++
All bitwise operators in one program
#include <iostream>
using namespace std;

int main() {
    int a = 5, b = 3;

    cout << "a & b = " << (a & b) << endl;
    cout << "a | b = " << (a | b) << endl;
    cout << "a ^ b = " << (a ^ b) << endl;
    cout << "~a = " << (~a) << endl;
    cout << "a << 1 = " << (a << 1) << endl;
    cout << "a >> 1 = " << (a >> 1) << endl;

    return 0;
}

Conclusion

C++ bitwise operators allow manipulation of individual bits of integers. Separate examples and a combined program demonstrate the behavior of &, |, ^, ~, <<, and >> operators.