Bitwise Operators

Bitwise operators allow performing operations on the single bits of the int and char types, possibly with modifiers applied. The operators are:
& AND
| OR
~ NOT
^ XOR
<< LEFT-SHIFT (new positions are filled with zero’s)
>> RIGHT-SHIFT (new positions are filled with zero’s)

In the following example, the variables:

unsigned int i = 15;
int j = 5;
are used as operands of the bitwise operators. NB:

15 is 1111 in binary
5 is 101 in binary

So 1111 & 0101 is 101, or 5 in decimal.
1111 | 0101 is 1111, or 15 in decimal.

The system we ran the program on has a 32 bit int type, so:
~ 1111 is 11111111111111111111111111110000, which in decimal is 4294967280.

101 << 2 means shift left by two positions, which evaluates to 10100, which is 20 in decimal.
1111 >> 3 means shift right by three positions, which evaluates to 1, which is 1 in decimal.


Example


#include <iostream>
using namespace std;

int main()
{   
     unsigned int i = 15;
     int j = 5;

     cout << (i & j) << endl;

     cout << (i | j) << endl;

     cout << ~ i << endl;

     cout << (i ^ j) << endl;

     cout << (j << 2) << endl;

     cout << (i >> 3) << endl;
}

Output

5
15
4294967280
10
20
1