liu*_*ori 3 java bit-manipulation
这是在long中实现rotateLeft:
public static long rotateLeft(long i, int distance) {
return (i << distance) | (i >>> -distance);
}
Run Code Online (Sandbox Code Playgroud)
但是,我无法理解(i >>> -distance)是如何工作的!有人可以告诉我怎么样!谢谢.
仅取得移位值的最低位.
这是一样的
return (i << (distance & 63)) | (i >>> (-distance & 63));
Run Code Online (Sandbox Code Playgroud)
要么
return (i << (distance & 63)) | (i >>> ((64-distance) & 63));
Run Code Online (Sandbox Code Playgroud)
要么
return (i << distance) | (i >>> (64-distance));
Run Code Online (Sandbox Code Playgroud)
使用负数的一个原因是它无论何种类型都可以工作,因此您可以在将来安全地更改它.
例如
// This works regardless of whether `x` is `int` or `long`
// and you can safely change the type in the future.
// 1 if negative, 0 if non-negative
x >>> -1;
// works for 32-bit but not 64-bit so if you change the type later,
// it could break without compiler error.
x >>> 31;
Run Code Online (Sandbox Code Playgroud)
你可能会发现这个有趣的http://vanillajava.blogspot.com/2012/01/shifting-challenge.html