C++ Bitwise Operators



In this section we are going to study C++ Bitwise operator, its importance and basic operating principle.

C++ Programming Bitwise Operators:

  • In programming, unlike byte level operations, we may need to do bit level calculations by operating on the individual data bit.
  • C++ gives us various bitwise operators for manipulation of bits.
  • C++ Bitwise Operators operates on Integer and character data types only.
  • C++ Bitwise Operators does not operates on float, double.
  • There are 6 Bitwise Operators in C++.

List of Bitwise Operators

Operator Name of Operator
~ One's Compliment
gt;gt; Right Shift
lt;lt; Left Shift
amp; Bitwise AND | Bitwise OR ^ Bitwise XOR

Examples of Bitwise Operators:

One's Compliment (~) Operator:

This operator is generally used to turn ON or turn OFF bit.

#include <iostream>
using namespace std;

int main()
{
   // 12 = 0000 1100
   unsigned int num1 = 12
   int num2 = 0;           

   num2 = ~num1;  
   cout << "Value of num2 is: " << num2 << endl ;

   return 0;
}

Output:

Value of num2 is: -13

Right Shift (>>) Operator:

This operator is used to shift the bits to right by position specified in the expression.

#include <iostream>
using namespace std;

int main()
{
   unsigned int num1 = 12; // 12 = 1100 
   int num2 = 0;           

   num2 = num1 >> 2; // 3 = 0011
   cout << "Value of num2 is: " << num2 << endl ;

   return 0;
}

Output:

Value of num2 is: 3

Left Shift (<<) Operator:

This operator is used to shift the bits to left by position specified in the expression.

#include <iostream>
using namespace std;

int main()
{
   unsigned int num1 = 12; // 12 = 0000 1100 
   int num2 = 0;           

   num2 = num1 << 2; // 48 = 0011 0010
   cout << "Value of num2 is: " << num2 << endl ;

   return 0;
}

Output:

Value of num2 is: 48

Bitwise AND (&):

This operator is generally used to mask particular part of byte.

Output:

Value of num2 is: 8
#include <iostream>
using namespace std;

int main()
{
   unsigned int num1 = 10;	  // 10 = 0000 1010  
   unsigned int num2 = 12;	  // 12 = 0000 1100
   int num3 = 0;           

   num3 = num1 & num2;         // 8 = 0000 1000
   cout << "Value of num3 is : " << num3 << endl ;

   return 0;
}

Bitwise OR (|):

#include <iostream>
using namespace std;

int main()
{
   unsigned int num1 = 10;	  // 10 = 0000 1010  
   unsigned int num2 = 12;	  // 12 = 0000 1100
   int num3 = 0;           

   num3 = num1 | num2;         // 14 = 0000 1110
   cout << "Value of num3 is : " << num3 << endl ;

   return 0;
}

Output:

Value of num2 is: 14

Bitwise XOR (^):

#include <iostream>
using namespace std;

int main()
{
   unsigned int num1 = 10;  // 10 = 0000 1010  
   unsigned int num2 = 12;  // 12 = 0000 1100
   int num3 = 0;           

   num3 = num1 ^ num2;      // 6 = 0000 0110
   cout << "Value of num3 is : " << num3 << endl ;

   return 0;
}

Output:

Value of num2 is: 6