Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect integer overflow on 32 bits int?

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 ?

like image 621
ashur Avatar asked Jan 20 '14 12:01

ashur


People also ask

How can you tell if an integer is overflow 32-bit?

To check for Integer overflow, we need to check the Integer. MAX_VALUE, which is the maximum value of an integer in Java. Let us see an example wherein integers are added and if the sum is more than the Integer. MAX_VALUE, then an exception is thrown.

How do you check if an integer is overflow?

Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1. The solution of casting to long and adding to find detecting the overflow is not allowed.

How do you check if a number is greater than 32-bit?

You cannot detect overflow of a 32 bit number by using a 32 bit number. If it is unsigned it will always be understood as a number between 0 and 2^32 -1. A overflowing input would still result is a valid out. A signed 32 bit value would be "valid" in the range 0 - 2^31-1.

How do you detect overflows?

Overflow Detection – So overflow can be detected by checking Most Significant Bit(MSB) of two operands and answer. But Instead of using 3-bit Comparator Overflow can also be detected using 2 Bit Comparator just by checking Carry-in(C-in) and Carry-Out(C-out) from MSB's. Consider N-Bit Addition of 2's Complement number.


1 Answers

Math.addExact throws exception on overflow

Since 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:

int x = 2_000_000_000; int y = 1_000_000_000; try {     int result = Math.addExact(x, y);     System.out.println("The proper result is " + result); } catch(ArithmeticException e) {     System.out.println("Sorry, " + e); } 

See this code run live at IdeOne.com.

Sorry, java.lang.ArithmeticException: integer overflow

like image 188
Patryk Czarnik Avatar answered Oct 07 '22 19:10

Patryk Czarnik