读书人

java位移运算符困惑

发布时间: 2012-12-26 14:39:28 作者: rapoo

java移位运算符困惑


private static final long WORD_MASK = 0xffffffffffffffffL;
public static void main(String[] args) {
int toIndex=70;
long lastWordMask = WORD_MASK >>> -toIndex;
System.out.println(lastWordMask);
}

为什么输出结果为63而将无符号右移改为>>结果为-1
[最优解释]
http://www.ticmy.com/?p=46
[其他解释]
摘自java语言规范:
The value of n >> s is n right-shifted s bit positions with sign-extension. The resulting value is ? n / 2s ?. For non-negative values of n, this is equivalent to truncating integer division, as computed by the integer division operator /, by two to the power s.

The value of n >>> s is n right-shifted s bit positions with zero-extension, where:

If n is positive, then the result is the same as that of n >> s.

If n is negative and the type of the left-hand operand is int, then the result is equal to that of the expression (n >> s) + (2 << ~s).

If n is negative and the type of the left-hand operand is long, then the result is equal to that of the expression (n >> s) + (2L << ~s).
[其他解释]
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.19
[其他解释]
引用:
http://www.ticmy.com/?p=46

谢谢了,终于弄懂了。这是BitSet源代码中的一段,琢磨了一天。

读书人网 >Java相关

热点推荐