最近我对位操作和算术产生了兴趣。我计划编写一段代码来使用 64 位长变量来表示棋盘,其中每个位代表一个单元格。
我遇到了以下问题:
public class Chess {
public static void main(String[] args) {
long v = (1 << 63 ) - 1;
System.out.println(Long.MAX_VALUE+ " " +v);
System.out.println(Long.toBinaryString(v));
System.out.println(Long.bitCount(v));
}
}
以下是上述代码的输出:
9223372036854775807 2147483647
1111111111111111111111111111111
31
这是不正确的。
我期待一个 64 位二进制字符串。我使用的是 64 位 Windows 操作系统的 64 位机器。
请帮忙。
最佳答案
您有一个 int
文字,因此当尝试按 63
进行位移动时,仅考虑 63
的最后 5 位 - - 31
。
使用long
文字(附加“L”)进行位移位:
long v = (1L << 63 ) - 1;
JLS, Section 15.19 ,涵盖位移细节:
If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance.
(强调我的)
这是有道理的 - int
中只有 32 位,即 2^5。
另外,
If the promoted type of the left-hand operand is long, then only the six lowest-order bits of the right-hand operand are used as the shift distance.
这又是有道理的——long
中有 64 位,即 2^6。
关于java - 无法在java中生成64位长值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21293575/