我怎样才能阻止发生OverflowException被扔在整数除法? [英] How can I stop OverflowException being thrown on integer division?

查看:205
本文介绍了我怎样才能阻止发生OverflowException被扔在整数除法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到发生OverflowException 的扔给我的时候,我不希望他们(我这样认为)。我进行了一些,我希望值溢出奇计算,丢弃溢出位。看来我不能得到这个正常工作,虽然。基本上,这是一对I和J这恰好是我遍历巨大的套(int.MinValue到int.MaxValue)。

I am getting OverflowException's thrown at me when I don't want them (or so I think). I am performing some odd calculations where I expect the values to overflow, discarding overflowed bits. It seems I can't get this to work properly though. Basically this is one pair of i and j which happens as I iterate over huge sets (int.MinValue to int.MaxValue).

// i and j are ints
// i is -2147483648
// j is -1
var x = i / j;

// I also tried using unchecked keyword, but it doesn't help    
var x = unchecked(i / j);

更新:

-2147483648 / -1预期的数学值是21​​47483648不过,这一定code并没有真正试图找到一些。这是一系列的走了有点难以理解位操作的事情的一部分。说实话,我甚至不知道自己的目的是什么,因为我真的没有记录的方法,以及时采取了1天远离它在我的头上引起严重WTF气泡。我只知道它的工作原理为目的的特殊code设计来处理这种情况。

The expected mathematic value of -2147483648 / -1 is 2147483648. However, this certain code doesn't really attempt to find the number. This is part of a series of bit manipulation things gone a bit hard to understand. To be honest, I don't even know myself what the intention was because I didn't really document the method, and all it took was one day away from it to raise serious WTF-bubbles over my head. All I know it works as intended with special code designed to handle the case.

关于预期值:

由于INT只能容纳2147483647它是最大的,我希望放弃溢出收益值0。

Since int can only hold 2147483647 at it's max, I expect to discard the overflow yielding value 0.

如果我已经了解这在所有东西,它可能是一些老旧方法的文档的重要性。

If I've learned anything about this at all, it's probably the importance of documentation for obscure methods.

推荐答案

我相信这是的只有的情况下,你会得到这个异​​常。这是的Int32 范围内唯一的划分,可以溢出。 (有按课程的零师,但是这是一个不同的异常。)

I believe this is the only case in which you'll get this exception. It's the only division within the Int32 range which can overflow. (There's division by zero of course, but that's a different exception.)

所以,如果你想避免发生OverflowException 你的只有的需要来处理这种情况。你想干什么就干什么?写这本插播的确切的情况下,否则不正常分裂。

So if you want to avoid OverflowException you only need to deal with this case. What do you want it to do? Write a method which spots this exact case, and otherwise does normal division.

注:这也是为什么你不应该试图扭转仅通过否定的结果进行比较。如果要排序的东西在使用 -compare(X,Y)使用降序排列,而不是上升,然后,而不是比较(Y,X) 。该否定的的给溢出 int.MinValue (除非你在checked上下文中) - 它只是默默地返回 int.MinValue

Note: this is also why you shouldn't try to reverse a comparison by just negating the result. If you want to sort something in descending order instead of ascending, then instead of using -Compare(x, y) use Compare(y, x). The negation doesn't give overflow for int.MinValue (unless you're in a checked context) - it just silently returns int.MinValue.

这篇关于我怎样才能阻止发生OverflowException被扔在整数除法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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