Integer.bitCount()的Java API告诉我们:
"public static 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));
}
}
Run Code Online (Sandbox Code Playgroud)
我得到这个输出:
Number = 255
Binary = 11111111
Two's Complement = 00000001
one bits of number = 8
我为什么得到8而不是1?
axt*_*avt 17
两个补语表示关于负数.正数的二进制补码表示该数字本身.
例如,Integer.bitCount(-1)返回32,因为两个补码表示-1是一个包含所有1s 的值(其中32个用于int).
但255不是负数,因此它的二进制补码表示是255本身的值(1其表示中有8 s).