简体   繁体   中英

Why does Integer.bitCount() return 8 for an input of 255?

The Java API for Integer.bitCount() tells us:

"public static int bitCount(int i)

Returns the number of one-bits in the two's complement binary representation of the specified int value. 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. Since: 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. 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
Binary = 11111111
Two's Complement = 00000001
Number of one bits = 8

Why am I getting 8 instead of 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 ).

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).

因为 8 是 11111111 中的位数。您采用正数的二进制补码的步骤无效。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM