在Java中多长时间int转换工作? [英] How does long to int cast work in Java?
本文介绍了在Java中多长时间int转换工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题是不如何长应该正确地转换为int ,而是当我们错误地将它转换为int时会发生什么。
This question is not about how a long should be correctly cast to an int, but rather what happens when we incorrectly cast it to an 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);
}
这将提供输出 -
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
推荐答案
以下是数学:
- 将
long
的值视为2 ^ 64
加上该值。因此,-1
被视为2 ^ 64 - 1.(这是无符号 64位值, - 取结果和mod 2 ^ 32。 (这是无符号 32位值。)
- 如果结果是> = 2 ^ 31,则减去2 ^ 32。 (这是签名的32位值,Java
int
。)
- Treat negative
long
values as2^64
plus that value. So-1
is treated as 2^64 - 1. (This is the unsigned 64-bit value, and it's how the value is actually represented in binary.) - Take the result and mod by 2^32. (This is the unsigned 32-bit value.)
- If the result is >= 2^31, subtract 2^32. (This is the signed 32-bit value, the Java
int
.)
这篇关于在Java中多长时间int转换工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文