Integer.bitCount()の Java APIは次のことを示しています。
"public static int bitCount(int i)
指定された int 値の 2 の補数バイナリ表現の 1 ビットの数を返します。この関数は、人口カウントと呼ばれることもあります。
戻り値: 指定された int 値の 2 の補数バイナリ表現の 1 ビットの数。以来: 1.5"
したがって、255 を 2 進数に変換すると、11111111 が得られます。これを 2 の補数バージョンに変換すると、00000001 が得られ、1 ビットの数は 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
2 の補数 = 00000001
1 ビットの数 = 8
1 ではなく 8 になるのはなぜですか?