Bitwise operators are used to perform a bit-level operation on operands. They are used in testing, setting, or shifting the actual bits in a program.
You can see the truth table below.
p | q | p & q | p | q | p ^ q | ~p |
---|---|---|---|---|---|
0 | 0 | 0 | 0 | 0 | 1 |
0 | 1 | 0 | 1 | 1 | 1 |
1 | 1 | 1 | 1 | 0 | 0 |
1 | 0 | 0 | 1 | 1 | 0 |
Below are the list of Bitwise operators:
Operators | Name of operators |
---|---|
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise XOR |
~ | Bitwise complement |
<< | Shift left |
>> | Shift right |
- The right shift operator (>>) shifts all bits towards the right by a certain number of specified bits.
- The left shift operator (<<) shifts all bits towards the left by a certain number of specified bits.
C++ Program for Bitwise operator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <iostream> using namespace std; int main() { unsigned int a = 60; // 60 = 0011 1100 unsigned int b = 13; // 13 = 0000 1101 int result = 0; result = a &b; // 12 = 0000 1100 cout << "& Operator: " << result << endl; result = a | b; // 61 = 0011 1101 cout << "| Operator: " << result << endl; result = a ^ b; // 49 = 0011 0001 cout << "^ Operator: " << result << endl; result = ~a; // -61 = 1100 0011 cout << "~ Operator: " << result << endl; result = a << 2; // 240 = 1111 0000 cout << "<< Operator: " << result << endl; result = a >> 2; // 15 = 0000 1111 cout << ">> Operator: " << result << endl; return 0; } |
Output:
1 2 3 4 5 6 | & Operator: 12 | Operator: 61 ^ Operator: 49 ~ Operator: -61 << Operator: 240 >> Operator: 1 |