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

pls help: a bit shift question

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
http://www.geocities.com/skmajji/Main.html
question #5:
The following code will print
1: int i = 1;
2: i <<= 31;<br /> 3: i >>= 31;
4: i >>= 1;
5:
6: int j = 1;
7: j >>= 31;
8: j >>= 31;
9:
10: System.out.println("i = " +i );
11: System.out.println("j = " +j);
A) i = 1
j = 1
B) i = -1
j = 1
C) i = 1
j = -1
D) i = -1
j = 0
why the answer is D? thanks in advance . I think i should be 0.
 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1: int i = 1; i is 1
2: i <<= 31; i is -1 (since the leftmost bit is 1)<br /> 3: i >>= 31; i is again 1
4: i >>= 1; i is -1, because the shift operation keeps
the sign of the number (as opposed to >>>)
Alex
 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

int i = 1; i = "00000000000000000000000000000001"
i<<=31; i = "10000000000000000000000000000000"<br /> i>>=31; i = "11111111111111111111111111111111"
i>>=1; i = "11111111111111111111111111111111"
so the result of i should be -1,
(2's complement of 00000000000000000000000000000001 )
wei
 
Alex Sbityakov
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I made a mistake in my earlier post. Wei's absolutely right.
But the point is your confusion stems from the fact that >> operator inserts 0 or 1 as the leftmost bit depending on the sign of the operand (in this case negative, so it fills in with 1's).
Alex
 
Rototillers convert rich soil into dirt. Please note that this tiny ad is not a rototiller:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic