簡體   English   中英

為什么 Integer.bitCount() 為 255 的輸入返回 8?

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

Integer.bitCount()的 Java API 告訴我們:

"public static 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
一位數 = 8

為什么我得到 8 而不是 1?

二進制補碼表示與負數有關。 正數的補碼表示是該數本身。

例如, Integer.bitCount(-1)返回 32,因為-1的二進制補碼表示是一個全為1的值(其中 32 個用於int )。

但是 255 不是負數,因此它的二進制補碼表示是值 255 本身(其表示中有 8 個1 )。

因為 8 是 11111111 中的位數。您采用正數的二進制補碼的步驟無效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM