This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes question on Shifting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "question on Shifting" Watch "question on Shifting" New topic
Author

question on Shifting

Veena Pointi
Ranch Hand

Joined: Jun 20, 2002
Posts: 442
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


SCJP1.4
"Continuous effort - not strength or intelligence - is the key to unlocking our potential."
*Winston Churchill
Sachin Tendulkar
Greenhorn

Joined: Sep 20, 2003
Posts: 27
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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: question on Shifting
 
Similar Threads
Convert negative integer to byte[] and back
bit shift
>>> operator
Bit Shifting
Reduction of the right operand