File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes how do we evaluate this???(shift operator) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "how do we evaluate this???(shift operator)" Watch "how do we evaluate this???(shift operator)" New topic

how do we evaluate this???(shift operator)

Amit Das
Ranch Hand

Joined: Mar 05, 2005
Posts: 206
hi all,

how do we evaluate this:
((23 << 10) >> -3)

what i dont understand here is how can we shift by -3

plz help,
Amit Das
Ranch Hand

Joined: Mar 05, 2005
Posts: 206
ammm.....i think whenever we have a -ive number on the right side of any shift operartor, we get a zero
Ariel Ortiz
Ranch Hand

Joined: May 14, 2004
Posts: 121
The JLS in section 15.19 says:

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & with the mask value 0x1F . The shift distance actually used is therefore always in the range 0 to 31, inclusive.


(x >> -3) == (x >> (-3 & 0x1F)) == (x >> 0x1D)

So, in your example:

((23 << 10) >> -3) == (23552 >> 0x1D) == 0

amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 812
can any body expain in more details pls...

with eg.. and illustration...

it would be gr8...
thanx in advance

Thanks and Regards, Amit Taneja
Jas Oberai
Ranch Hand

Joined: Jan 16, 2005
Posts: 231
Hi Amit,
To make sure that the value always falls in 0-31(inclusive) range,the compiler masks it with 0x1F,the explanation has been provided by Ariel,I am showin you the example in detail:

I have thought of a short-cut method,but i dont knw how far it would work.
For eg.
if it's x >> -3,it changes to x >> 29 (i.e 32-3).
For,x << -4,it changes to x << 28 (i.e 32 - 4).
lolz..hopes that helps!!!

SCJP 1.4 (88%)<br />SCWCD 1.4 (88%)
Animesh Shrivastava
Ranch Hand

Joined: Jul 19, 2004
Posts: 298
Also one more thing, if the shift number is a long variable like as in here shown below, the compiler masks it 0X3F.
Amit Das
Ranch Hand

Joined: Mar 05, 2005
Posts: 206
hi animesh,
i think you've given a wrong examle

its the promoted type left-hand operand which has to be a long and not the RHS(in ur case) for the compiler to use the mask 0x3f.
I agree. Here's the link:
subject: how do we evaluate this???(shift operator)
jQuery in Action, 3rd edition