Java 中的按位运算使用相似的代码给出不同的值?
Bitwise operations in Java give different value with similar code?
简短的问题。我对在 Java 中执行 bit/bytewise 操作很陌生,但我注意到了一些奇怪的事情。
下面的代码给出了输出:
2
0
代码:
String[] nodes = new String[3];
boolean in;
int index = 0;
int hash = "hi".hashCode();
in = (nodes[(index = nodes.length - 1) & hash]) != null;
System.out.println(index);
index = (nodes.length - 1) & hash;
System.out.println(index);
为什么在第 5 行和第 7 行代码中为索引赋值的操作相同,但索引具有不同的值?
正如我所说,我是 bitwise/bytewise 操作的新手,所以我可能缺少一些背景信息。
您对 index
的第一个赋值发生在此处的括号中:
in = (nodes[(index = nodes.length - 1) & hash]) != null;
这是
index = nodes.length - 1
并且值为 "two"。您的第二个作业 (index = (nodes.length - 1) & hash;
) 不同;您添加了一个 & hash
,它可能有两位 0
,因此当您执行按位 &
时,它变成 0
。
(index = nodes.length - 1) & hash
将 nodes.length - 1
分配给 index
,然后 bitwise-ands 它与 hash
。
index = (nodes.length - 1) & hash
bitwise-andsnodes.length - 1
与hash
,然后将结果赋值给index
.
不是一回事。
简短的问题。我对在 Java 中执行 bit/bytewise 操作很陌生,但我注意到了一些奇怪的事情。
下面的代码给出了输出:
2
0
代码:
String[] nodes = new String[3];
boolean in;
int index = 0;
int hash = "hi".hashCode();
in = (nodes[(index = nodes.length - 1) & hash]) != null;
System.out.println(index);
index = (nodes.length - 1) & hash;
System.out.println(index);
为什么在第 5 行和第 7 行代码中为索引赋值的操作相同,但索引具有不同的值?
正如我所说,我是 bitwise/bytewise 操作的新手,所以我可能缺少一些背景信息。
您对 index
的第一个赋值发生在此处的括号中:
in = (nodes[(index = nodes.length - 1) & hash]) != null;
这是
index = nodes.length - 1
并且值为 "two"。您的第二个作业 (index = (nodes.length - 1) & hash;
) 不同;您添加了一个 & hash
,它可能有两位 0
,因此当您执行按位 &
时,它变成 0
。
(index = nodes.length - 1) & hash
将 nodes.length - 1
分配给 index
,然后 bitwise-ands 它与 hash
。
index = (nodes.length - 1) & hash
bitwise-andsnodes.length - 1
与hash
,然后将结果赋值给index
.
不是一回事。