Search code examples
javamathexpressioninteger-overflow

Calculate Java Int Overflow


Is there a formula to calculate what the overflow of a Java int would be?

Example: if I add 1 to Integer.MAX_VALUE; the answer is not 2147483648, but rather -2147483648.

Question: if I wanted to calculate what Java would print for a value larger than 2^32, is there an easy mathematical expression (theoretical, not in code)?


Solution

  • ((x + 231) mod 232) - 231

    Is this what you're looking for? That should be the result of any mathematical operation on a machine that uses 32-bit signed 2's complement integers. That is, if the mathematical value of an operation returns x, the above formula gives the integer that would actually be stored (if the operation doesn't fault, and it's not a "saturating" operation).

    Note that I'm using "mod" with a mathematical definition, not the way the % operator works in Java or C. That is, A mod B, where A and B are integers and B > 0, always returns an integer in the range 0 .. B-1, e.g. (-1) mod 5 = 4. More specifically, A mod B = A - B*floor(A/B).