Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent integer overflow in Java code? [duplicate]

Possible Duplicate:
How can I check if multiplying two numbers in Java will cause an overflow?

Suppose I have a Java class method, which uses * and + operations.

 int foo(int a, int b) {   ... // some calculations with + and *  } 

How to make sure that no overflow occurs in foo?

I guess I can either use BigDecimal or replace all + and * with "wrappers" like:

 int sum(int a, int b) {    int c = a + b;    if (a > 0 && b > 0 && c < 0)       throw new MyOverfowException(a, b)    return c; }  int prod(int a, int b) {    int c = a * b;    if (a > 0 && b > 0 && c < 0)       throw new MyOverfowException(a, b)    return c; } 

Are there better ways to make sure that no int overflow occurs in a Java method ?

like image 398
Michael Avatar asked Sep 01 '12 09:09

Michael


1 Answers

One way to check for an overflow is to have the operands promoted to a larger type (of double the original operand bit length) then perform the operation, and then see if the resulting value is too large for the original type, e.g.

int sum(int a, int b) {     long r = (long)a + b;     if (r >>> 32 != 0) {    // no sign extension         throw new MyOverflowException(a, b);     }     return (int)r; } 

If your original type is a long, you'd have to use BigInteger as that larger type.

like image 115
Alnitak Avatar answered Oct 10 '22 19:10

Alnitak