Integer.bitCount()的 Java API告诉我们:
“公共静态 int bitCount(int i)
返回指定 int 值的二进制补码表示中的一位数。这个函数有时被称为人口计数。
返回: 指定 int 值的二进制补码表示中的一位数。自:1.5"
因此,如果我们将 255 转换为二进制,我们得到 11111111。如果我们将其转换为二进制补码版本,我们得到 00000001,使一位数为 1。但是,如果我运行此代码:
import java.lang.*;
public class IntegerDemo {
public static void main(String[] args) {
int i = 255;
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));
/* The next few lines convert the binary number to its two's
complement representation */
char[] tc= Integer.toBinaryString(i).toCharArray();
boolean firstFlipped = true;
for (int j = (tc.length - 1); j >= 0; j--){
if (tc[j] == '1'){
if(firstFlipped){
firstFlipped = false;
}
else{
tc[j] = '0';
}
}
else {
tc[j] = '1';
}
}
// Casting like this is bad. Don't do it.
System.out.println("Two's Complement = " + new String(tc));
System.out.println("Number of one bits = " + Integer.bitCount(i));
}
}
我得到这个输出:
Number = 255
Binary = 11111111
Two's Complement = 00000001
Number of one bits = 8
为什么我得到 8 而不是 1?