aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Shift Operation with negative operand Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Shift Operation with negative operand" Watch "Shift Operation with negative operand" New topic
Author

Shift Operation with negative operand

Ruben Lunda
Greenhorn

Joined: Aug 27, 2004
Posts: 5
I dont understand the logic of this operation, when the second value is negative, like:

I try it in this
Applet

but i dont undertand it.
thanks
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Good question! Here's what I found:

"...when the value to be shifted (left-operand) is an int, only the last 5 [binary] digits of the right-hand operand are used to perform the shift. The actual size of the shift is the value of the right-hand operand masked by 31 ... [so] the shift distance is always between 0 and 31."

Ref: http://www.janeg.ca/scjp/oper/shift.html


In binary, an int of -1 is:
11111111 11111111 11111111 11111111

Taking only the last 5 digits, we get:
00000000 00000000 00000000 00011111

...which is 31.

Therefore (1 << -1) is equivalent to (1 << 31).

Hmmm... Who knew?
[ September 16, 2004: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Ruben Lunda
Greenhorn

Joined: Aug 27, 2004
Posts: 5
Thank you marc! that makes it all clear!!!
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
A small add-on to marc's post: it's 6 bits for shifting a long.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
No, bytes and shorts are promoted to ints. Check out your basic Java book about this.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Shift Operation with negative operand