File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question on Shifting

 
Veena Pointi
Ranch Hand
Posts: 442
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int a =-8;
int b=~-33;
a>>>=b;
System.out.println(a);
above code prints -8 ,how?Can anybody please explain?
Is expression like 8>>-4 valid?how to solve questions that involve shifting with negative numbers?
thanks
Veena
 
Sachin Tendulkar
Greenhorn
Posts: 27
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int a =-8;
int b=~-33;
a>>>=b;
System.out.println(a);
above code prints -8 ,how?Can anybody please explain?
Is expression like 8>>-4 valid?how to solve questions that involve shifting with negative numbers?
thanks
Veena

Step 1) a>>=b is expanded to
a = (int) (a >> b)
Step 2) b = ~-33
= -(-33) - 1
= 33 - 1
b = 32
(remember ~x = -(x) - 1)
Step 3) a = (int) (a >> 32)
32 in binary is represented as
00000000 00000000 00000000 00100000
When shifting numbers if the type is int then the number of places to shift is denoted by the top 5 bits of the number to shift by
in this case the top 5 bits of 32 are 00000 which is 0
so in short the expression is reduced to
Step 4) a = (int) (a >> 0)
a = (int) a
a = -8
HTH
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic