How long to work in Java?

This question is not about how long should be correctly added to the int , but rather what happens when we cast it to the int incorrectly.

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 result -

 longNumber = 9223372036854775807 intNumber = -1 

Now suppose I make the following change -

 long longNumber = Long.MAX_VALUE - 50; 

Then I get the output -

 longNumber = 9223372036854775757 intNumber = -51 

The question is , how is a long value that converts to int?

+24
java casting
Sep 19 '12 at 19:12
source share
1 answer

The low 32 bits of long are taken and placed in int .

Here is the math though:

  • Treat negative long values ​​as 2^64 plus this value. Thus, -1 treated as 2 ^ 64 - 1. (This is an unsigned 64-bit value, and how it is actually represented in binary format.)
  • Take the result and mod at 2 ^ 32. (This is a 32-bit unsigned value.)
  • If the result> = 2 ^ 31, subtract 2 ^ 32. (This is a signed 32-bit value, Java int .)
+35
Sep 19 '12 at 19:13
source share



All Articles