Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does (i >>> -distance) work

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.

like image 410
liuxiaori Avatar asked Mar 08 '26 01:03

liuxiaori


1 Answers

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

like image 104
Peter Lawrey Avatar answered Mar 09 '26 13:03

Peter Lawrey