JLS (15.19 Shift Operators) states:- The value of n>>s is n right-shifted s bit positions with sign-extension. The resulting value is (n/2^s). For nonnegative values of n, this is equivalent to truncating integer division, as computed by the integer division operator /, by two to the power s.

Question:- If I want to compute for a negative value of n, i.e -8 >> s what is the procedure... is there a formula that holds true for negative values? e.g how would I calculate:- (1) -8 >> 31 (2) -8 >> -3

this is really confusing i tried doing this 2<<3; 2<<-3; both give different ans. How do you shift nos having negative sign on right hand side. Someone please help Reagrds neha

OK the first thing to point out is that: if the left-hand side is an int then the right-hand side is ANDed with 0x1F and if the left-hand side is a long then the right-hand side is ANDed with 0x3F. Now, let's take a look at 2<<3 and 2<<-3. 2<<3 : No suprises here the result is 16 as expected. BUT for 2<<-3 the story is different. the right-hand side (-3) in binary is 11111111 11111111 11111111 11111101 and ANDed with 0x1F it gives 11101 which is in fact 29 (32-3) and the result of the shifting is 1073741824. To summarize: the right-hand side is in all cases ANDed with 0x1F (or 0x3F) and that result is the one used in the shifting operation. So there is no way to shift more than 31 positions (to the left or to the right) because of that AND operation whatever the sign of the rigth-hand side is. HIH

------------------ Valentin Crettaz Sun Certified Programmer for Java 2 Platform

Great ,i was not at all aware of this nor did it ever strike me. thanks Rosie for removing this topic and Thanks to Valentin for the great explanation Regards neha