What does this bit shift operation means in Java RegularEnumSet implementation?

StackOverflow https://stackoverflow.com/questions/13466092

  •  30-11-2021
  •  | 
  •  

문제

In RegularEnumSet implementation, there is a code:

elements = -1L >>> -universe.lengh

It uses a Long type integer to implement efficient EnumSet.

What is notable is that the right-hand operand of >>> is a negative figure.

I have tested and found that

int i = -1;
i >>> -3  

has equivalent effect with

int i = 1;
i << 3;

So why bother to write in this ambiguous form?

도움이 되었습니까?

해결책

From the "Java Language Specification", section 15.19, about shifting "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-and operand were subjected to a bitwise logical AND operator & with the mask value 0x3f. The shift distance actually used is therefore awlays 0 to 64, inclusive."

So, >>> -3 has equivalent effect as >>> 61, and -1L >>> -n equals -1L >>> (0x3f&-n)

Actually this seems to be the most effective way of producing a consecutive 1s in the lowest n-bits of a long integer.

다른 팁

First, note that the code you quoted uses -1L, not -1. Longs are unsigned, so -1L is equivalent to setting all the bits on the long, or getting the highest possible long number.

>>> -3 has equivalent effect with << 3

It doesn't. The unsigned right shift operator (>>>) shifts zeroes into the sign bit, while >> and << preserve the sign of the value being shifted, shifting 1 or 0 accordingly. That's why -1L >>> -3 is 7 (0111b) and 1L << 3 is 8 (1000b).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top