Check out Manning's Countdown to 2014. Use discount code crdotd14 all month for 50% off every deal.
Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# Negative operand in shift operation

Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
Hello.
Can I someone explain to me how to solve a shift operation which involves a negative right operand.
For example: 9 >> -3
Is the negative sign ignored? Help.
Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
Hi again. Can someone shed some light on this? Thanks.
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Gaia
On the actual test I didn't see anything that hard, nor do I recall hearing anyone that did either. However, to clear up your confusion:
The right hand operand in a shift expression first has an & 0x1F applied to it, this ensures that the range is within 0-31 for integers. For longs it is & 0x3f to get it between 0 and 63. When dealing with positive right side operand that is the same as doing a %32 (or 64 for longs) and shifting by the result.
When the operand is negastive though the % operator doesn't have the same effect. In that case it is best to do the & 0x1F to get the result. In the few example I tried it looks to me like the result of this when using a negative number is 32 + the number.
So for example -2 & 0x1F would be 32 + -2 = 30. I know this wont work for negative numbers below 32 - someone here with a little more math or binary experience can probably answer that. Of course you can always work them out by hand too, it only takes a minute.
hope that helps a little bit, if not let me know and I can elaborate

------------------
Dave
Sun Certified Programmer for the Javaï¿½ 2 Platform

Dave
Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
Hi Dave. Thanks a lot for your reply. Yes, it does clear up my confusion to some extent.
quote:
The right hand operand in a shift expression first has an & 0x1F applied to it, this ensures that the range is within 0-31 for integers. For longs it is & 0x3f to get it between 0 and 63. When dealing with positive right side operand that is the same as doing a %32 (or 64 for longs) and shifting by the result.
end quote.
I understand that you mean that for right-hand operands bigger than 32, the %32 operation is applied to it. For operands bigger than 64, the %64 operation is applied to it.
Does this mean that the right-hand operand can be a long?
Thanks again.

[This message has been edited by Gaia Nathan (edited September 06, 2001).]

I agree. Here's the link: http://aspose.com/file-tools

subject: Negative operand in shift operation