java - 无法在java中生成64位长值

标签 java 64-bit

最近我对位操作和算术产生了兴趣。我计划编写一段代码来使用 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/

相关文章:

java - 适用于桌面应用程序的最佳开源轻量级 "Packagable"DB

java - JSObject.getWindow(this);总是抛出异常

c++ - ftell 非常大文件的错误

C# 为什么 127 = 这个位串?

visual-studio - System.BadImageFormatException-无法解决

node.js - 在node.js中随机访问大文件(需要支持64位文件偏移量)?

java - 哪个 jar 和 spring 版本<mvc :resource> come?

java - Tomcat JDCBRealm 找不到驱动程序类

java - 如何使用外部类名调用非静态内部类

c - 如何在 Windows 上检测进程的体系结构?