[英]Why does Integer.bitCount() return 8 for an input of 255?
The Java API for Integer.bitCount() tells us: Integer.bitCount()的 Java API 告诉我们:
"public static int bitCount(int i) "public static int bitCount(int i)
Returns the number of one-bits in the two's complement binary representation of the specified int value.返回指定 int 值的二进制补码表示中的一位数。 This function is sometimes referred to as the population count.
此函数有时称为人口计数。
Returns: the number of one-bits in the two's complement binary representation of the specified int value.返回: 指定 int 值的二进制补码表示中的一位数。 Since: 1.5"
自:1.5"
So if we take 255 and convert it to binary, we get 11111111. If we convert that to the two's complement version we get 00000001, making the number of one-bits one.因此,如果我们取 255 并将其转换为二进制,我们将得到 11111111。如果我们将其转换为二进制补码版本,我们将得到 00000001,从而使一位的数量为 1。 However, if I run this code:
但是,如果我运行此代码:
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));
}
}
I get this output:我得到这个输出:
Number = 255数字 = 255
Binary = 11111111二进制 = 11111111
Two's Complement = 00000001补码 = 00000001
Number of one bits = 8一位数 = 8
Why am I getting 8 instead of 1?为什么我得到 8 而不是 1?
Two's complement represenation is about negative numbers.二进制补码表示与负数有关。 Two's complement representation of a positive number is that number itself.
正数的补码表示是该数本身。
For example, Integer.bitCount(-1)
returns 32, because two's complement representation of -1
is a value with all 1
s (32 of them for int
).例如,
Integer.bitCount(-1)
返回 32,因为-1
的二进制补码表示是一个全为1
的值(其中 32 个用于int
)。
But 255 is not a negative number, therefore its two's complement representation is the value 255 itself (that has 8 1
s in its representation).但是 255 不是负数,因此它的二进制补码表示是值 255 本身(其表示中有 8 个
1
)。
因为 8 是 11111111 中的位数。您采用正数的二进制补码的步骤无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.