2

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 になるのはなぜですか?

4

2 に答える 2

19

2 の補数表現は、負の数に関するものです。正数の 2 の補数表現は、その数そのものです。

たとえば、Integer.bitCount(-1)は 32 を返します。これは、 の 2 の補数表現が-1すべて1s ( の場合は 32 個) を持つ値であるためintです。

しかし、255 は負の数ではないため、その 2 の補数表現は値 255 そのものです (1その表現には 8 があります)。

于 2014-01-31T21:16:49.280 に答える