Bitwise Operators in C++

As the name says, bitwise operators are used to perform operations on bits. Bit is the smallest unit memory. A bit represents 2 unique combinations of binary numbers.

  • 0 (boolean zero)
  • 1 (boolean one)

Decimal values are converted into binary values (which are the sequence of bits) and bit wise operators work on these bits.

Types of Bitwise Operators :

C++ provides 3 bitwise operators –

Bitwise Operators

Truth Table for Bitwise Operators :

The Truth table for Bitwise Operators will be –

x y  x|y x & y x ^ y
0 0 0 0 0
0 1 1 0 1
1 0 1 0 1
1 1 1 1 0

Example of Bitwise Operators :

Consider an example, assume 0=31 and p=21

o = 0 0 0 1 1 1 1 1    (31 in decimal)
p = 0 0 0 1 0 1 0 1     (21 in decimal)

(o & p)  AND Operator Working
   o=  0 0 0 1 1 1 1 1    (31 in decimal)
   p=  0 0 0 1 0 1 0 1    (21 in decimal)
       ---------------- 
(o&p)= 0 0 0 1 0 1 0 1 
       ----------------
(o | p)  OR Operator Working
    o= 0 0 0 1 1 1 1 1    (31 in decimal) 
    p= 0 0 0 1 0 1 0 1    (21 in decimal) 
       ----------------  
(o|p)= 0 0 0 1 1 1 1 1 
       ----------------
(o ^ p)  XOR Operator Working
    o= 0 0 0 1 1 1 1 1    (31 in decimal) 
    p= 0 0 0 1 0 1 0 1    (21 in decimal) 
       ----------------  
(o^p)= 0 0 0 0 1 0 1 1 
       ----------------
(~o)  Negate/Bitwise Not Operator Working
 x= 0 0 0 1 1 1 1 1    (31 in decimal) 
~x= 1 1 1 0 0 0 0 0

Example of C++ program for Bitwise Operators –

#include <iostream.h>
int main()
    {
    int o = 31,p = 21,AND,OR,XOR,NOT;
    AND = (o&p);
    OR  = (o|p);
    NOT = (~o);
    XOR = (o^p);
    cout<<"AND Operator value = "<<AND <<endl;
    cout<<"OR Operator value = "<<OR <<endl;
    cout<<"NOT Operator value = "<<NOT <<endl;
    cout<<"XOR Operator value = "<<XOR <<endl;
    return 0;
    }
Output – 
AND Operator value = 21
OR Operator value = 31
NOT Operator value = -32
XOR Operator value = 10
Explanation of Output :
21 = 0 0 0 1 0 1 0 1
31 = 0 0 0 1 1 1 1 1 

and operator will result 0 0 0 1 0 1 0 1 = (21)10
or operator will result 0 0 0 1 1 1 1 1 = (31)10
NOT operator will result 1 1 1 0 0 0 0 0 = (-32)10
XOR operator will result 0 0 0 0 1 0 1 0 = (10)10
     

Leave a Reply