java - (i >>> -distance) 是如何工作的

标签 java bit-manipulation

这是 Long 中 rotateLeft 的实现:

public static long rotateLeft(long i, int distance) {
   return (i << distance) | (i >>> -distance);
}

但是,我不明白 (i >>> -distance) 是如何工作的!谁能告诉我怎么做!谢谢。

最佳答案

只取移位值的最低位。

这和

是一样的
return (i << (distance & 63)) | (i >>> (-distance & 63));

return (i << (distance & 63)) | (i >>> ((64-distance) & 63));

return (i << distance) | (i >>> (64-distance));

使用负数的一个原因是它与类型无关,因此您可以在将来安全地更改它。

例如

// 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;

您可能会发现这很有趣 http://vanillajava.blogspot.com/2012/01/shifting-challenge.html

关于java - (i >>> -distance) 是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9513074/

相关文章:

java - 从 32 位 java 运行 64 位 Windows 命令

java - 由于方法大小过大,无法对 jprofiler 进行检测

C - 使用按位运算符将 int 显示为十六进制

assembly - 从最高有效位或高位开始提取寄存器的位

java - 通过 0 位操作清除 i 中的位

c# - 如何测试按位枚举是否包含 C# 中另一个按位枚举的任何值?

java - thymeleaf 中字符串的参数

java - java GC如何清理相互关联的对象

java - 替换扫描字符串中的特定单词并使用 Java 中的 substring() 连接

java - 按位加法在 Java 上有效,但在 Ruby 上失败