2014-01-20 2 views
0

그와 같은 주제가 여러 번 묻는 것을 알고 있지만 내 질문은 전체의 32 비트에서 오버플로에 대해입니다. 예를 들어 : 어떻게 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 비트를 넘으면 예외가 발생합니다. Math 클래스의 메소드 세트가 자바 8 때문에

Boolean ifExceeds32Bit = CheckIfIntExceeds32Bit(4294967296); 

public boolean CheckIfIntExceeds32Bit(int num) 
{ 

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

: 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); 
}