C++ Bitwise Operators
Bitwise operators in C++ are used to perform operations on individual bits of integer values. They are useful in low-level programming, such as systems programming, embedded systems, and performance-critical applications.
List of Bitwise Operators
| Operator | Description | Example |
|---|---|---|
| & | Bitwise AND – sets each bit to 1 if both bits are 1 | 5 & 3 // 0101 & 0011 = 0001 (1) |
| | | Bitwise OR – sets each bit to 1 if one of the bits is 1 | 5 | 3 // 0101 | 0011 = 0111 (7) |
| ^ | Bitwise XOR – sets each bit to 1 if only one bit is 1 | 5 ^ 3 // 0101 ^ 0011 = 0110 (6) |
| ~ | Bitwise NOT – inverts all the bits | ~5 // 0101 -> 1010 (depends on system representation) |
| << | Left Shift – shifts bits to the left, fills 0 on the right | 5 << 1 // 0101 << 1 = 1010 (10) |
| >> | Right Shift – shifts bits to the right, fills 0 or sign bit on the left | 5 >> 1 // 0101 >> 1 = 0010 (2) |
Example Program
#include <iostream>
using namespace std;
int main() {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
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;
}
Output
a & b = 1 a | b = 7 a ^ b = 6 ~a = -6 a << 1 = 10 a >> 1 = 2
Important Notes
- Bitwise operators work only with integer types (int, char, long, etc.).
- The ~ operator produces the two’s complement of the number.
- Bitwise shifts (<<, >>) are often used for fast multiplication or division by powers of 2.
- Bitwise operators are widely used in low-level programming, embedded systems, and performance-critical applications.
Next Topic
After learning all C++ operators, you can continue with C++ Control Structures (if-else, loops) for building logic in programs.