Java – long long is not greater than long MAX_ VALUE

If I have a mission

Long c = a + b;

Is there a simple way to check that a B is no better than long MAX_ VALUE / Long. MIN_ Value larger / smaller?

Solution

Using guava, it's so simple

long c = LongMath.checkedAdd(a,b); // throws an ArithmeticException on overflow

This is what I want. It's really readable (LongMath Javadoc here.)

To be fair, I'll mention that Apache commons provides arithmetics utils addAndCheck(long,long).

If you want to know how they work, the answer is guava's little hacker: if (a ^ b) < 0 | (a ^ (a b)) > = 0 This is a technique based on the bitwise XOR of two numbers if they have the nonnegativity of the same sign

So (a ^ b) if a and B have different symbols, it is 0. If so, it will never overflow Alternatively, if (a ^ (a, b)) > = 0, B has the same symbol as a, so it does not overflow and becomes negative

(for more tips like this, investigate the lovely book hacker's delight.)

Apache uses more complex files based on the symbols of a and B

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>