• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

shift question

 
bani kaali
Ranch Hand
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code will print
1: int i = 1;
2: i <<= 31;
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);
Ans is i = -1 and j =0;
could any one tell me how i is -1 ?
 
Chung Huang
Ranch Hand
Posts: 56
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
modify your code as follows:

each output line shows the binary representation of i.
Note, the first line shows 1 as its binary representation because the leading zeros are omitted.
Hope this helped. But basically it has to do with the fact that int has 32-bit size, and the left most bit is the sign bit that also happens to be the padding bit for >>. Remember >>> uses zero as its padding bit regardless of the sign bit.
 
bani kaali
Ranch Hand
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I didnt know about toBinaryString() .Thanks chung for helping me .
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic