The right and left shift operators are useful in eliminating bits from the number.
Right Shift Operator(>>)
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 right operand.
Syntax:
<decimal> >> <no. the bits to be shifted>
Example
7 >> 2
it means, in decimal number 7, 2 bits are shifted right.
Binary equivalent - 0000000000000111
7>>2 gives 0000000000000001
Example:
| Original number | right shifted no. |
|
| 9>>1 | 0000000000001001 | 0000000000000100 |
| 9>>2 | 0000000000001001 | 0000000000000010 |
| 9>>3 | 0000000000001001 | 0000000000000001 |
| 9>>4 | 0000000000001001 | 0000000000000000 |
- If operand is multiple of 2,then shifting the operand one bit to the right is same as dividing it by 2 and ignoring the remainder.
Example
64 >> 1 gives 32
32>> 2 gives 8
27>>1 gives 13
47 >> 1 gives 23
- In a>>b, if b is negative,the result is unpredictable. If a is negative then its left most bit would be 1.
Example
-1 >> 2
-1 (binary) 1111111111111111
-1 >> 2 0011111111111111
Left Shift Operator( << )
The only difference is that the bits are shifted to left,a 0(zero) is added to the right of the number.
Example
7 << 2
7 -> 0000 0000 0000 0111
7<<2 -> 0000 0000 0001 1100




Recent Comments