Long + Long不大于Long.MAX_VALUE [英] Long + Long not bigger than Long.MAX_VALUE
问题描述
如果我有任务
Long c = a + b;
是否有一种简便的方法来检查a + b
是否大于或小于Long.MAX_VALUE
/Long.MIN_VALUE
?
Is there an easy way to check that a + b
is not bigger/smaller than Long.MAX_VALUE
/Long.MIN_VALUE
?
推荐答案
long c = LongMath.checkedAdd(a, b); // throws an ArithmeticException on overflow
我想想,
确实非常易读. (LongMath Javadoc 此处.)
For the sake of fairness, I'll mention that Apache Commons provides ArithmeticUtils.addAndCheck(long, long)
.
如果您想知道它们的工作原理,那么答案是番石榴的一小撮比特黑客:如果(a ^ b) < 0 | (a ^ (a + b)) >= 0
,结果不会溢出.这是基于以下技巧:如果两个数字的符号相同,则它们的按位XOR运算将为非负数.
If you want to know how they work, well, the answer is one line of bit-hackery for Guava: the result doesn't overflow if (a ^ b) < 0 | (a ^ (a + b)) >= 0
. This is based on the trick that the bitwise XOR of two numbers is nonnegative iff they have the same sign.
因此,如果a
和b
具有不同的符号,则(a ^ b) < 0
为true,并且在这种情况下,它将永远不会溢出.或者,如果(a ^ (a + b)) >= 0
,则a + b
与a
具有相同的符号,因此它不会溢出并变为负数.
So (a ^ b) < 0
is true if a
and b
have different signs, and if that's the case it'll never overflow. Or, if (a ^ (a + b)) >= 0
, then a + b
has the same sign as a
, so it didn't overflow and become negative.
(有关此类的更多技巧,请研究可爱的书 Hacker's Delight .)
(For more tricks like this, investigate the lovely book Hacker's Delight.)
Apache根据a
和b
的符号使用更复杂的案例.
Apache uses more complicated casework based on the sign of a
and b
.
这篇关于Long + Long不大于Long.MAX_VALUE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!