位置:首页 > Java技术 > java.lang > java.lang.Integer.numberOfLeadingZeros()方法实例

java.lang.Integer.numberOfLeadingZeros()方法实例

java.lang.Integer.numberOfLeadingZeros() 方法返回零位的最高位(“最左侧”)之前的数中指定的int值的二进制补码表示一比特。

它返回32,如果指定的值没有一个比特在它的2的补码表示的,换句话说,如果它等于零。

声明

以下是java.lang.Integer.numberOfLeadingZeros()方法的声明

public static int numberOfLeadingZeros(int i)

参数

  • i -- 这是int值。

返回值

此方法返回零位的最高位(“最左侧”)前在指定的int值的二进制补码表示法,或32个1位的数量,如果该值为零。

异常

  • NA

例子

下面的例子显示java.lang.Integer.numberOfLeadingZeros()方法的使用。

package com.yiibai;

import java.lang.*;

public class IntegerDemo {

   public static void main(String[] args) {

     int i = 170;
     System.out.println("Number = " + i);
    
     /* returns the string representation of the unsigned integer value 
     represented by the argument in binary (base 2) */
     System.out.println("Binary = " + Integer.toBinaryString(i));

     // returns the number of one-bits 
     System.out.println("Number of one bits = " + Integer.bitCount(i));

     /* returns an int value with at most a single one-bit, in the position 
     of the highest-order ("leftmost") one-bit in the specified int value */
     System.out.println("Highest one bit = " + Integer.highestOneBit(i));

     /* returns an int value with at most a single one-bit, in the position
     of the lowest-order ("rightmost") one-bit in the specified int value.*/
     System.out.println("Lowest one bit = " + Integer.lowestOneBit(i));

     /*returns the number of zero bits preceding the highest-order 
     ("leftmost")one-bit */
     System.out.print("Number of leading zeros = ");
     System.out.println(Integer.numberOfLeadingZeros(i));
   }
}

让我们来编译和运行上面的程序,这将产生以下结果:

Number = 170
Binary = 10101010
Number of one bits = 4
Highest one bit = 128
Lowest one bit = 2
Number of leading zeros = 24