如何检测32位整数上的整数溢出? [英] How can I detect integer overflow on 32 bits int?

查看:719
本文介绍了如何检测32位整数上的整数溢出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有人多次问过这个话题,但是我的问题是关于完整32位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 ?

推荐答案

Math.addExact在溢出时引发异常

自Java 8起, Math 类:

Math.addExact throws exception on overflow

Since Java 8 there is a set of methods in the Math class:

...以及很长的版本.

…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.

添加示例:

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

请参见此在IdeOne.com上实时运行的代码.

对不起,java.lang.ArithmeticException:整数溢出

Sorry, java.lang.ArithmeticException: integer overflow

这篇关于如何检测32位整数上的整数溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆