在 Java 中 int 转换的时间有多长?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12501331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does long to int cast work in Java?
提问by CodeBlue
This question is notabout how a long should be correctly cast to an int, but rather what happens when we incorrectly cast it to an int.
这个问题不是关于long 应该如何正确转换为 int,而是当我们错误地将它转换为 int 时会发生什么。
So consider this code -
所以考虑这个代码 -
@Test
public void longTest()
{
long longNumber = Long.MAX_VALUE;
int intNumber = (int)longNumber; // potentially unsafe cast.
System.out.println("longNumber = "+longNumber);
System.out.println("intNumber = "+intNumber);
}
This gives the output -
这给出了输出 -
longNumber = 9223372036854775807
intNumber = -1
Now suppose I make the following change-
现在假设我进行了以下更改-
long longNumber = Long.MAX_VALUE - 50;
I then get the output -
然后我得到输出 -
longNumber = 9223372036854775757
intNumber = -51
The question is, howis the long's value being converted to an int?
问题是,long 的值是如何转换为 int 的?
回答by Louis Wasserman
The low 32 bits of the long
are taken and put into the int
.
的低 32 位long
被取出并放入int
.
Here's the math, though:
不过,这是数学:
- Treat negative
long
values as2^64
plus that value. So-1
is treated as 2^64 - 1. (This is the unsigned64-bit value, and it's how the value is actually represented in binary.) - Take the result and mod by 2^32. (This is the unsigned32-bit value.)
- If the result is >= 2^31, subtract 2^32. (This is the signed 32-bit value, the Java
int
.)
- 将负值
long
视为2^64
加上该值。因此-1
被视为 2^64 - 1。(这是无符号的64 位值,它是该值实际以二进制表示的方式。) - 将结果和 mod 乘以 2^32。(这是无符号的32 位值。)
- 如果结果 >= 2^31,则减去 2^32。(这是有符号的 32 位值,即 Java
int
。)