C++ Bitwise Operators

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.

pqp & qp | qp ^ q~p
000001
010111
111100
100110

Below are the list of Bitwise operators:

OperatorsName 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

#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:

& Operator: 12
| Operator: 61
^ Operator: 49
~ Operator: -61
<< Operator: 240
>> Operator: 1