简体   繁体   English

如何在Java中使用Java进行工作?

[英]How does long to int cast work in Java?

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. 这个问题不是关于如何将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, how is the long's value being converted to an int? 问题是,long的值如何转换为int?

The low 32 bits of the long are taken and put into the int . 所述的低32位long取并投入int

Here's the math, though: 不过这是数学:

  1. Treat negative long values as 2^64 plus that value. 将负long值视为2^64加上该值。 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.) 因此-1被视为2 ^ 64 - 1.(这是无符号的 64位值,它实际上是以二进制表示的值。)
  2. Take the result and mod by 2^32. 取结果和mod 2 ^ 32。 (This is the unsigned 32-bit value.) (这是无符号的 32位值。)
  3. If the result is >= 2^31, subtract 2^32. 如果结果> = 2 ^ 31,则减去2 ^ 32。 (This is the signed 32-bit value, the Java int .) (这是带符号的32位值,即Java int 。)

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

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