How does long to int cast work in Java?

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.)

Leave a Comment