this is the implecation of rotateLeft in Long:
public static long rotateLeft(long i, int distance) {
return (i << distance) | (i >>> -distance);
}
but,i can't understand how does (i >>> -distance) work! somebody who can tell me how! thank you.
Only the lowest bits of the shifting value are taken.
This is the same as
return (i << (distance & 63)) | (i >>> (-distance & 63));
or
return (i << (distance & 63)) | (i >>> ((64-distance) & 63));
or
return (i << distance) | (i >>> (64-distance));
One reason to use a negative number is that it works regardless of type so you can safely change it in the future.
e.g.
// 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;
You might find this interesting http://vanillajava.blogspot.com/2012/01/shifting-challenge.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With