2014-01-20 55 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); 
}