programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# shift

Greenhorn
Posts: 11
-5>>-2

Sheriff
Posts: 21208
87
-5 >> -2

Let's assume these are ints - it could work for longs as well but then you'll use 64 bits instead of 32.

-5 in bit notation is
1111 1111 1111 1111 1111 1111 1111 1011

Now please note that the shift will always be modulo 32 for ints and modulo 64 for longs. Therefore, -5 >> -2 is equal to -5 >> 30

So all bits are shifted 30 places to the right, filling the left with the left-most bit of the original, 1:
1111 1111 1111 1111 1111 1111 1111 1111
Of this number, which is -1, only the last two bits are taken from the original.

Now if you want to add zeros at the start, use >>> instead of >>. This will result in:
0000 0000 0000 0000 0000 0000 0000 0011
which is 3.

Ranch Hand
Posts: 1970
Well, I didn't know that. Here's the relevant bit in the JLS: -

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 & (�15.22.1) with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

If the promoted type of the left-hand operand is long, then only the six 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 & (�15.22.1) with the mask value 0x3f. The shift distance actually used is therefore always in the range 0 to 63, inclusive.

Now, who can tell me what on Earth the point of this is?

Rob Spoor
Sheriff
Posts: 21208
87
Ignoring everything after the 5th / 6th bit will do the same as modulo.

I think they did this because the sizes of int and long are 32 and 64 bit respectively, and the people who invented Java didn't see any logic in shifting more than 31 / 63 (basically making your number either 0 or -1) or shifting less than 0 (shifting the other way around).
Of course the modulo is kinda weird; if I'd want to right shift an integer 33 I'd want 0 or -1, not half the number I had.

 Beware the other head of science - it bites! Nibble on this message: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS