简体   繁体   English

Java为什么要砍掉这个长整数的高阶位?

[英]Why does Java chop off the higher-order bits of this long?

Consider the following code: 请考虑以下代码:

System.out.println(1 + 0xFFFFFFFFL);
System.out.println(1L + 0xFFFFFFFF);

The first line prints the expected value, 4294967296 . 第一行打印预期值4294967296 But the second line prints a 0 . 但是第二行显示0 I checked the type of both expressions (by passing them to methods) and both are recognized as long by the JVM. 我检查两个表达式的类型(通过它们传递给方法),并都被作为公认long由JVM。 The Lava 7 language specification states that with binary operations, "if either operand is of type long, the other is converted to long." Lava 7语言规范指出,对于二进制操作,“如果任一操作数的类型为long,则另一个操作数转换为long”。 It seems that's what is happening, but I have two questions: 这似乎正在发生,但我有两个问题:

  1. If both operands end up being longs, why are the higher-order bits chopped off in the first expression? 如果两个操作数最终都是long,为什么第一个表达式中的高阶位被切断?

  2. Why should the order matter? 为什么订单很重要?

0xFFFFFFFF is equal to -1 . 0xFFFFFFFF等于-1 When you add 1 + -1 you get 0. 1 + -1时得到0。

The order matters because 0xFFFFFFFFL != (long) 0xFFFFFFFF 顺序很重要,因为0xFFFFFFFFL != (long) 0xFFFFFFFF

Just like (double) 0.1F != 0.1 就像(double) 0.1F != 0.1

By default, in java all numeric constants are int . 默认情况下,在java中,所有数字常量都是int

In the second example, because java uses the two's-complement binary representation, the expression 0xFFFFFFFF is -1 as an int , which when widened to a long stays as -1 , so you've coded 1 + -1 , giving zero. 在第二个例子中,因为java使用二进制补码二进制表示,所以表达式0xFFFFFFFF-1作为int ,当加宽到long保持为-1 ,所以你编码1 + -1 ,给出零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM