JDK源码之Integer类—signum()方法

sginum()方法的功能是确定输入的数的符号,如果输入的是正数则返回1,如果输入的是零则返回0,如果输入的是负数则返回-1

例如:

public class Test {
    public static void main(String[] args) {
        System.out.println(Integer.signum(18));// 1
        System.out.println(Integer.signum(0));// 0 
        System.out.println(Integer.signum(-35));// -1
    }
}

该方法的源码是:

    /**
     * Returns the signum function of the specified {@code int} value.  (The
     * return value is -1 if the specified value is negative; 0 if the
     * specified value is zero; and 1 if the specified value is positive.)
     *
     * @param i the value whose signum is to be computed
     * @return the signum function of the specified {@code int} value.
     * @since 1.5
     */
    public static int signum(int i) {
        // HD, Section 2-7
        return (i >> 31) | (-i >>> 31);
    }

对该方法进行注释如下:

    /**
     * 返回指定int值的符号函数(所谓的符号函数就是确定输入值的符号【正数|负数|0】)
     * 如果指定值为负数,则返回值为-1;如果指定值为0,则返回值为0;如果指定值为正数,则返回值为1
     *
     * @param i 要计算其符号的值
     * @return 返回指定int值的符号,如果是负数返回-1,0返回0,正数返回1
     */
    public static int signum(int i) {
        // 如果是正数,则可以通过(-i >>> 31)确定符号,即获取最高位的符号。因为(i >> 31)会为0。
        // 如果是负数,则可以通过(i >> 31)确定符号,即获取最高位的符号。因为(-i >>> 31)会为0。
        return (i >> 31) | (-i >>> 31);
    }

对该方法的源码进行模拟过程如下:

/*
(i >> 31) | (-i >>> 31)
第一种情况:i是正数,则返回1。例如i=96所对应的二进制是0000 0000 0000 0000 0000 0000 0110 0000
        i=0000 0000 0000 0000 0000 0000 0110 0000
    i>>31=0000 0000 0000 0000 0000 0000 0000 0000
       -i=1111 1111 1111 1111 1111 1111 1010 0000
  -i>>>31=0000 0000 0000 0000 0000 0000 0000 0001
(i >> 31) | (-i >>> 31)
          0000 0000 0000 0000 0000 0000 0000 0000
         |
          0000 0000 0000 0000 0000 0000 0000 0001
         =0000 0000 0000 0000 0000 0000 0000 0001
第二种情况:i是0,则返回0。
第三种情况:i是负数,则返回-1。例如i=-96所对应的二进制是1111 1111 1111 1111 1111 1111 1010 0000
        i=1111 1111 1111 1111 1111 1111 1010 0000
    i>>31=1111 1111 1111 1111 1111 1111 1111 1111
       -i=0000 0000 0000 0000 0000 0000 0110 0000
  -i>>>31=0000 0000 0000 0000 0000 0000 0000 0000
(i >> 31) | (-i >>> 31)
          1111 1111 1111 1111 1111 1111 1111 1111
         |
          0000 0000 0000 0000 0000 0000 0000 0000
         =1111 1111 1111 1111 1111 1111 1111 1111
 */

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值