zoukankan      html  css  js  c++  java
  • -2147483648的绝对值

    求整型绝对值的有以下方法:

    1. int abs = a > 0 ? a : -a;
    2. 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
  • 相关阅读:
    js实现将字符串里包含手机号的中间四位替换为****
    草稿for套for
    js实现将时间戳转换成2017-05-06 09:03:02
    时间日期校验接口
    JS延迟导航nav
    nav导航
    鼠标滚动请求加载
    常用开源Jabber(XMPP) IM服务器介绍(转)
    01.base-v1.js
    Haproxy安装及配置(转)
  • 原文地址:https://www.cnblogs.com/cdbb/p/13252034.html
Copyright © 2011-2022 走看看