JDK源码之Integer类—signum()方法
  TEZNKK3IfmPf 2023年11月13日 27 0

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
 */

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   24天前   51   0   0 java
  TEZNKK3IfmPf   2024年05月31日   30   0   0 脚本jdk
  TEZNKK3IfmPf   2024年05月31日   55   0   0 java
TEZNKK3IfmPf