I know such topic was asked several times, but my question is about overflow on full 32 bits of int. For example:
11111111111111111111111111111111 +
00000000000000000000000000000001 =
00000000000000000000000000000000 //overflow!
I found topic with similar question about this, however the algorithm is not perfect.
11111111111111111111111111111111 +
00000000000000000000000000000000 =
00000000000000000000000000000000 //overflow!
Is there any simple, fast, safer way to check this ?
Try this way:
From: https://wiki.sei.cmu.edu/confluence/display/java/NUM00-J.+Detect+or+prevent+integer+overflow
The most intuitive method I can think of: calculate the sum (or difference) as a
long
, then convert that sum to anint
and see if its value has changed.Remember that on modern 64 bit processors, working with
long
s is no less efficient than working withint
s (the opposite may be true). So if you have a choice between checking for overflows or usinglong
s, go for the latter.Overflow can be detected by a logical expression of the most significant bit of the two operands and the (truncated) result (I took the logical expression from the MC68030 manual):
Math.addExact
throws exception on overflowSince Java 8 there is a set of methods in the
Math
class:toIntExact(long)
addExact(int,int)
subtractExact(int,int)
multiplyExact(int,int)
…and versions for long as well.
Each of these methods throws
ArithmeticException
if overflow happens. Otherwise they return the proper result if it fits within the range.Example of addition:
See this code run live at IdeOne.com.