Java告诉我们:
“公共静态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));
}
} 我得到了这个输出:
编号= 255
二进制= 11111111
二补数= 00000001
1位数=8位
为什么我得到的是8而不是1?
发布于 2014-01-31 21:16:49
二的补码表示是关于负数的。正数的补表示是正数本身。
例如,Integer.bitCount(-1)返回32,因为两个-1的补码表示是一个包含所有1s的值(其中32个表示int)。
但是255不是负数,因此它的两个补码表示是值255本身(它的表示中有8个1s )。
发布于 2014-01-31 21:32:42
因为8是11111111的位数。你采取正数的两个补数的步骤是无效的。
https://stackoverflow.com/questions/21490117
复制相似问题