• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Left shift and the sign bit (MSB)... tutorial error???

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I came across 2 tutorial pages where it says that for a left or right shift (<< and >>) the sign bit will never change.
I tested this with the Bit By Bit applet at http://www.javaranch.com/campfire/StoryBits.jsp
I tried 2 << 30 (integer 2 left shifted by 30 bits) and the result is : -2147483648. (a negative)
Both pages came from the jchq.net site.
From http://www.jchq.net/tutorial/05_01Tut.htm
"The left and right shift operators move the bit pattern to the left or right and leave the sign bit alone."
From http://www.jchq.net/tutorial/BitShift.htm
"Thus a left or right shift (<< and >>) will never cause a number to change its sign. A positive number will always stay positive and a negative number will always stay negative."

Am I missing anything or these two quotes are misleading?
Thanks!
 
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
byte & short values (& also char) are promoted to int when an expression is evaluated which means that the outcome of a left shift on a byte or short will result in an int.
That said , here are the binary representations -
00000000000000000000000000000010 --> 2
01000000000000000000000000000000 --> 2 << 29
Now , 2 << 30 will yield
10000000000000000000000000000000 --> 2 << 30
And hence the negative value.

"Thus a left or right shift (<< and >>) will never cause a number to change its sign. A positive number will always stay positive and a negative number will always stay negative."


I beleive the quotes are wrong . Only a right shift ( >> ) can help with preserving the sign of a number.
[This message has been edited by Ashish Hareet (edited August 25, 2001).]
 
Mark Brossard
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Ashish,
I wonder if Marcus Green has been already notified about this?
I'll check the discussion group on his site.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic