2014-01-20 51 views
0

我知道这样的话题被问了好几次,但我的问题是关于整个32位int溢出。例如:我怎么能检测到32位的整数溢出

11111111111111111111111111111111 + 
    00000000000000000000000000000001 = 
    00000000000000000000000000000000 //overflow! 

我发现topic有类似的问题,但这个算法并不完美。

11111111111111111111111111111111 + 
    00000000000000000000000000000000 = 
    00000000000000000000000000000000 //overflow! 

有没有简单快捷的方法来检查?

+2

https://www.securecoding.cert.org/confluence/display/java/NUM00-J.+Detect+or+prevent+integer+overflow –

回答

2
long test = (long)x+y; 
if (test > Integer.MAX_VALUE || test < Integer.MIN_VALUE) 
    // Overflow! 
0

溢出可通过两个操作数和(截短的)结果的最显著比特的逻辑表达式来检测(I把从MC68030手册逻辑表达式):

/** 
* Add two int's with overflow detection (r = s + d) 
*/ 
public static int add(int s, int d) throws ArithmeticException { 
    int r = s + d; 
    if (((s & d & ~r) | (~s & ~d & r)) < 0) 
     throw new ArithmeticException("int overflow add(" + s + ", " + d + ")"); 
    return r; 
} 
-2

最简单的方法是,将该值赋给try块内的整数变量。如果超过32位,则会抛出异常。

Boolean ifExceeds32Bit = CheckIfIntExceeds32Bit(4294967296); 

public boolean CheckIfIntExceeds32Bit(int num) 
{ 

try 
    { 
    int testVal = num; 
    return false; 
    }catch(Exception e) 
    { 
    return true; 
    } 
} 
1

由于Java 8有一组在Math类方法: toIntExact(长),addExact(INT,INT),subtractExact(INT,INT),multiplyExact (int,int)以及版本。 如果发生溢出,它们会抛出ArithmeticException,如果它适合范围,它们会返回正确的结果。加入

实施例:

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