• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Shift Operation with negative operand

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Ruben Lunda
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you marc! that makes it all clear!!!
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A small add-on to marc's post: it's 6 bits for shifting a long.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, bytes and shorts are promoted to ints. Check out your basic Java book about this.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic