求整型绝对值的有以下方法:
int abs = a > 0 ? a : -a;
Math.abs()
函数
以int整型为例,取值范围是-2147483648 ~ 2147483647
,对于-2147483647 ~ 2147483647
范围内的数字,使用上面的方法没有问题,但是对于-2147483648
取绝对值的时候却会直接返回该值。
以下是Java中Math.abs()
函数的源码
/**
* Returns the absolute value of an {@code int} value.
* If the argument is not negative, the argument is returned.
* If the argument is negative, the negation of the argument is returned.
*
* <p>Note that if the argument is equal to the value of
* {@link Integer#MIN_VALUE}, the most negative representable
* {@code int} value, the result is that same value, which is
* negative.
*
* @param a the argument whose absolute value is to be determined
* @return the absolute value of the argument.
*/
public static int abs(int a) {
return (a < 0) ? -a : a;
}
/**
* Returns the absolute value of a {@code long} value.
* If the argument is not negative, the argument is returned.
* If the argument is negative, the negation of the argument is returned.
*
* <p>Note that if the argument is equal to the value of
* {@link Long#MIN_VALUE}, the most negative representable
* {@code long} value, the result is that same value, which
* is negative.
*
* @param a the argument whose absolute value is to be determined
* @return the absolute value of the argument.
*/
public static long abs(long a) {
return (a < 0) ? -a : a;
}
下面是各个值的二进制:
值 | 二进制 |
---|---|
-2147483647原码 | 1111 1111 1111 1111 1111 1111 1111 1111 |
-2147483647补码 | 1000 0000 0000 0000 0000 0000 0000 0001 |
-1原码 | 1000 0000 0000 0000 0000 0000 0000 0001 |
-1补码 | 1111 1111 1111 1111 1111 1111 1111 1111 |
-2147483648 补码 | 1000 0000 0000 0000 0000 0000 0000 0000 |