Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

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

Amit Das
Ranch Hand
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,
thanx
amit

Amit Das
Ranch Hand
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
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.

Thus:

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

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

...Ariel

amit taneja
Ranch Hand
Posts: 813
can any body expain in more details pls...

with eg.. and illustration...

it would be gr8...

Jas Oberai
Ranch Hand
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!!!

Animesh Shrivastava
Ranch Hand
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
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.