How does long to int cast work in Java?

痞子三分冷 提交于 2019-12-17 15:53:45

问题


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);
    }

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?


回答1:


The low 32 bits of the long are taken and put into the int.

Here's the math, though:

  1. Treat negative long values as 2^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.)
  2. Take the result and mod by 2^32. (This is the unsigned 32-bit value.)
  3. If the result is >= 2^31, subtract 2^32. (This is the signed 32-bit value, the Java int.)


来源:https://stackoverflow.com/questions/12501331/how-does-long-to-int-cast-work-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!