Shift Operators in C++

Shift Operators in C++ (<< and >>) –

Left Shift Operator in C++-

Rotate left - Shift Operators

Right Shift Operator in C++ –

Rotate Right-Shift Operator

How do we apply shifting on unsigned and signed numbers ?

Applying shifting on unsigned/positive numbers –

(x<<2)  Left Shift Operator Working
   x =    0 0 0 1 1 1 1 1    (31 in decimal)
x<<1 =    0 0 1 1 1 1 1 0    
x<<2 =    0 1 1 1 1 1 0 0
(x>>2)  Right Shift Operator Working
   x = 0 0 0 1 1 1 1 1    (31 in decimal) 
x>>1 = 0 0 0 0 1 1 1 1     
x>>2 = 0 0 0 0 0 1 1 1

Applying shifting on signed numbers –

if the operand is a signed value, then arithmetic shift will be used.

if x is negative and the sign bit is 1, so 1’s are shifted from the most significant end. If x is non-negative, 0’s are shifted from the most significant end. This is called an arithmetic right shift since the sign bit is shifted in.

Negative numbers are represented by 2’s complement. To apply 2’s complement to a decimal number –

  • convert decimal number into Binary form.
  • take 1’s complement of the binary form  i.e. (invert the bits).
  • Add Binary 1 to 1’s complement, and the result coming out will be 2’s complement.

An example of shifting on signed numbers are –
Let z = -20  (minus 20)

2’s Complement and Left Shift – 

0 0 0 1 0 1 0 0  (20 in binary)
1's complement of 20 =        1 1 1 0 1 0 1 1  (invert bits)
Adding 1 to 1's complement =+ 0 0 0 0 0 0 0 1  
                            ------------------- 
2's complement of z        =  1 1 1 0 1 1 0 0   (-20 in binary)
Left shift (<<)            =  1 1 0 1 1 0 0 0
converting left shift result into decimal by applying 2's complement again -
2's complement of left shift result = 0 0 1 0 1 0 0 0 = 40 
and adding minus sign =-40 (Answer)

Right Shift – 

0 0 0 1 0 1 0 0  (20 in binary)
2's complement of z        =  1 1 1 0 1 1 0 0   (-20 in binary)
Right shift (>>)           =  1 1 1 1 0 1 1 0
converting arithmetic right shift result into decimal by applying 2's complement again -
2's complement of right shift result = 0 0 0 0 1 0 1 0 = 10 
and adding minus sign =-10 (Answer)

Example of C++ program for Shift Operators –

#include <iostream.h>
int main()
    {
    int a = 8;
    int b = -8;    
    int c = 0; 
    c = a >> 1; 
    cout<<"Right shift of a by 1 = "<< c <<endl ;
    c= b >>1;
    cout<<"Right Shift of b by 1 = "<< c <<endl; 
    c= b << 1;
    cout<<"Left Shift of a = "<< c <<endl; 
    c = a << 1; 
    cout<<"Left shift of b = "<< c <<endl;
    return 0;
}
Output – 
Right shift of a by 1 = 4
Right Shift of b by 1 = -4
Left Shift of a = -16
Left shift of b = 16
     

Leave a Reply