posted 20 years ago
Hi Sridhar,
lets take an eg like this:
int i = -3;
i<<2;
i>>2;
i>>>2;
since all the negative values r represented in two's complement form,
binary represenattion of i = 0000 0000 0000 0000 0000 0000 0000 0011
binary represenattion of -3 is given in two's complement form as
-3 = 1111 1111 1111 1111 1111 1111 1111 1101( applying bitwise inversion and adding one to the obtained value)
now applying shift operators to i;
i<<2 - shifting left by two bits and appending 0's at the end.we get
i<<2 = 1111 1111 1111 1111 1111 1111 1111 0100
sice the result obtained is a negative no, agan it has to be represented in two's complement form.so, we will get
i<<2 = 0000 0000 0000 0000 0000 0000 0000 1100 - this is equivalent to 12 and since it is a negative no the ans will be -12.
so, finally -3<<2 = -12;
coming to -3>>2 - shifting -3 by two bits and appending the sign bits at the Most significant bits we will get
-3 = 1111 1111 1111 1111 1111 1111 1111 1101
-3>>2 = 1111 1111 1111 1111 1111 1111 1111 1111 (sice -3 is negative, introducing 1's in most significant bits)
as already seen, the result is agn a negative value and so taking the two's complement form,we get
-3>>2 = 0000 0000 0000 0000 0000 0000 0000 0001
so, the result of -3>>2 is -1
now, -3>>>2 - applying unsigned rigth shift by two bits( introducing zeros at MSB)
-3 = 1111 1111 1111 1111 1111 1111 1111 1101
-3>>>2 = 0011 1111 1111 1111 1111 1111 1111 1111
here no need to take two's complemet of the result ,as the result is a positive no. so, we can directly take the decimal representation of the obtained binary result.
Hope this will help u.
vineela.