public static int rotateLeft(int i, int distance) {
return (i << distance) | (i >>> -distance);
}
问题:
请教一下:移动运算的位数是负数是如何计算的?!谢了!!
...全文
6232打赏收藏
请教java移位运算问题:当移动位数是负数是怎么计算?不胜感激!!!
问题描述: 在java的源代码中,java.lang.Integer.java中循环左移的实现如下所示: public static int rotateLeft(int i, int distance) { return (i <>> -distance); } 问题: 请教一下:移动运算的位数是负数是如何计算的?!谢了!!
i<<-1和i<<31 的结果一样
1 “-1”表示成补码是1111 ....11 1111 ,31是 0000 ...0011 1111,,他们的后六位是一样的。
2 Interger的移位运算只注意后6位,看注释
Note also that rotation by any multiple of 32 is a no-op, so all but the last five bits of the rotation distance can be ignored, even if the distance is negative:
总结:将负数写为补码,这个数的低6位便是其真正移位的数字。