Java.lang.Integer 类

java.lang.Integer.bitCount() 方法返回 2 的补码二进制表示形式中的一位数指定的 int 值。此函数有时称为人口计数。

语法

public static int bitCount(int i)

参数

i 指定要计算位的值。

返回值

返回一的个数指定 int 值的二进制补码二进制表示形式中的位。

异常

无。

示例:

在下面的示例中,java.lang.Integer.bitCount() 方法返回给定 int 值的二进制补码二进制表示形式中的一位数。

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //创建int值
    int x = 135;

    //打印x
    System.out.println("The x is = " + x);     

    //打印x的二进制表示
    System.out.println("The x in binary is = " + Integer.toBinaryString(x)); 

    //打印x中一位的数量
    System.out.println("Number of one bits in x = " + Integer.bitCount(x)); 
  }
}

上述代码的输出将是:

The x is = 135
The x in binary is = 10000111
Number of one bits in x = 4