Originally posted by Manish Hatwalne:
-8 >> -2 = -1 and
-8 << 2 = -32<br /> Why would they be same? As a thumb rule, whenever you shift to left the value gets doubled with every shift, and when you shift to right value gets halved (1/2th, 1/4th 1/8th etc) with every shift.<br /> However, since only last 5 bits of the RHS (Right Hand Side) operand are used by the shift operators, -8 >> -2 is effectively -8 >> 30. I think, Gururaj has described a much better way of arriving at it. As for me, I am pretty comfortable with bits and bytes, so I look at it this way. Sorry if I have confused you.
[This message has been edited by Manish Hatwalne (edited October 03, 2001).]
Originally posted by Manish Hatwalne:<br /> Hi,<br /> Regarding bit shift opertors, important thing is [b]only last 5 bits of the RHS operand are used. A signed right shift operator >> does not change sign of the operand on the LHS.
Now consider this -
-8 in binary => 11111111111111111111111111111000
-2 in binary => 11111111111111111111111111111110
-8 >> -2 gets converted to -8 >> 30 (last 5 bits of -2, 11110 makes 30)
so, we have
-8 (11111111111111111111111111111000) >> 30 (11110)
Shifting 30 times to the right we get all 1s (signed right shift) which is -1. (all 1s in binary)
Similarly, for -8 << -2 you get
-8 << 30
i.e. -8 (11111111111111111111111111111000) << 30 (11110)
which is 0.
Try this code -
public class Scratch
public static void main(String args)
System.out.println("-8 = " + Integer.toBinaryString(-8));
System.out.println("-2 = " + Integer.toBinaryString(-2));
System.out.println("-8 >> -2 = " + (-8 >> -2));
System.out.println("-8 << -2 = " + (-8 << -2));
In the SCJP exam however, I believe the bit shift operations will not be very comlicated and will have operands which you can compute manually w/o using calculator or something.
If you are still confused abt. negative nos. have a look at this.
[This message has been edited by Manish Hatwalne (edited October 02, 2001).][/B]