How does long to int cast work in Java?

后端 未结 1 1570
谎友^
谎友^ 2020-12-05 13:37

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 conside

相关标签:
1条回答
  • 2020-12-05 14:14

    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.)
    0 讨论(0)
提交回复
热议问题