Friday, November 4, 2011

Right Shift Operator in C programming

Right Shift Operator

The right shift operator is represented by >>. It needs two operands. It shifts each bit in its left operand to the right. The number of places the bits are shifted depends on the number following the operator (i.e. its right operand).
Thus, ch >> 3 would shift all bits in ch three places to the right. Similarly, ch >> 5 would shift all bits 5 places to the right.
For example, if the variable ch contains the bit pattern 11010111, then, ch >> 1 would give 01101011 and ch >> 2 would give 00110101.
Note that as the bits are shifted to the right, blanks are created on the left. These blanks must be filled somehow. They are always filled with zeros. The following program demonstrates the effect of right shift operator.

main( )
{
int i = 5225, j, k ;
printf ( "\nDecimal %d is same as binary ", i ) ;
showbits ( i ) ;
for ( j = 0 ; j <= 5 ; j++ )
{
k = i >>j ;
printf ( "\n%d right shift %d gives ", i, j ) ;
showbits ( k ) ;
}
}
The output of the above program would be...
Decimal 5225 is same as binary 0001010001101001
5225 right shift 0 gives 0001010001101001
5225 right shift 1 gives 0000101000110100
5225 right shift 2 gives 0000010100011010
5225 right shift 3 gives 0000001010001101
5225 right shift 4 gives 0000000101000110
5225 right shift 5 gives 0000000010100011
Note that if the operand is a multiple of 2 then shifting the operand one bit to right is same as dividing it by 2 and ignoring the remainder. Thus,
64 >> 1 gives 32
64 >> 2 gives 16
128 >> 2 gives 32
but,
27 >> 1 is 13
49 >> 1 is 24 .

A Word of Caution

In the explanation a >> b if b is negative the result is unpredictable. If a is negative than its left most bit (sign bit) would be 1. On some computer right shifting a would result in extending the sign bit. For example, if a contains -1, its binary representation would be 1111111111111111. Without sign extension, the operation a >> 4 would be 0000111111111111. However, on the machine on which we executed this expression the result turns out to be 1111111111111111. Thus the sign bit 1 continues to get extended.

No comments:

Post a Comment