• 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

Shift operator

 
Ranch Hand
Posts: 582
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
I have code
int i = 1;
i <<=31;<br /> i >>=31;
Why the answer of i is -1 ? Can you give me some explaantions about it?
thanks
daniel
 
Ranch Hand
Posts: 2596
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
int i = 1;
i <<=31;<br /> i >>=31;
Neither produces -1
i >>=31 is 0 as expected.
i <<=31; gives -2147483648, because if you shift 1(one) 31 times to its left, it leads to 1 as MSB (Most Significant Bit), the righmost bit with all others as zero. This MSB indicates negative number, hence the resullt. The result will be different if i is of type long. The negative result is due to overflow, as range of an int is 32 bits.
HTH,
- Manish
[This message has been edited by Manish Hatwalne (edited October 10, 2001).]
 
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you shift the bit all the way to the left, it moves into the "sign" bit -- all negative numbers have a 1 there (see twos compliment notation, anyplace on the web for details).
When you use >> it not only moves the set bit to the right, it "extends" the sign bit, so you go from:
0000 0000 0000 0000 0000 0000 0000 0001
to
1000 0000 0000 0000 0000 0000 0000 0000
(a very very big negative number)
then >> to:
1111 1111 1111 1111 1111 1111 1111 1111
which is, of course minus 1.
Clever eh? If you dont understand, then you really need to look up 2s compliment notation (http://burks.brighton.ac.uk/burks/foldoc/42/120.htm)
James
 
Manish Hatwalne
Ranch Hand
Posts: 2596
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh, I C.
I took them one by one and was wondering which one produced -1 for you.
It does produce the reult as James explains. The signed right shift operator >> does not change sign of the number, hence MSB remains as 1.
- Manish
 
reply
    Bookmark Topic Watch Topic
  • New Topic