This week's book giveaway is in the Jobs Discussion forum. We're giving away four copies of Soft Skills and have John Sonmez on-line! See this thread for details.

can any body explain what actually happens when we shift bits by a negative number? eg: 13 >> -2 = 0 1000 >>> -25 = 7 1000 >>> -2 = 0 1000 >> -25 = 7 etc.....

Java only uses the portion of the right-hand operand that applies (5 bits if it's an int, 6 bits if it's a long).

For example, -2 in binary is 1111...110 (imagine a string of 1's where those ellipses are). If we're shifting an int, Java only takes the 5 right-most bits, or 11110, which is 30 in binary. So,

13 >> -2 13 >> 30

are identical statements.

There's a Javaranch article on this topic at here. Here's the pertinent portion:

Well, in Java, ints are "signed" variables (they can be positive or negative), so this is a legal line of code:

byte b = 13; b = (byte)(b >> -6);

So now the question is, what does that do? Does it shift left instead of right? Does it give an error? Actually, it does neither. When performing a shift, only a portion of the right hand operand is used. If you're shifting an int, you'll use only the right-most 5 bits of the shift value. That means that the amount you shift by will always fall within the range of 0 and 31. If you're shifting a long, you'll use only the right-most 6 bits of the shift value. In that case, your shift distance falls within 0 and 63. Let's see how that works with our last example:

-6 in binary is 11111010

We're shifting an int (remember that anything smaller than an int is promoted to an int) so we use only the right-most 5 bits of that value. Therefore, we're shifting by 26 (11010 in binary is 26 in decimal). So, our previous line equates to this:

b = (byte)(b >> 26);

Of course, if we shift 13 to the right by 26 positions, we've managed to push all of the real data off the table and replaced it with zeros. So, in the end, we have b equal to 0. [ August 19, 2005: Message edited by: Ryan Kade ]

Then 1000 would fall off and all zeros will be left how answer is 7?

nagaraju

Here, 1000 is not binary representation of decimal 8 it is one thousand Rest you can do the math of bit shifting.. which will yield you 7.

Cheers,<br />Jay<br /> <br />(SCJP 1.4)<br />Heights of great men were not achieved in one day, they were toiling day and night while their companions slept.