首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么输入为255时Integer.bitCount()返回8?

为什么输入为255时Integer.bitCount()返回8?
EN

Stack Overflow用户
提问于 2014-01-31 21:10:58
回答 2查看 4.2K关注 0票数 2

Java告诉我们:

“公共静态int bitCount(int i)

返回指定int值的互补二进制表示中的一位数。这一职能有时被称为人口计数。

返回:指定的int值的互补二进制表示中的一位数。自: 1.5“

因此,如果我们取255个,并将其转换为二进制,则得到11111111。如果我们把它转换成两个的补码版本,我们得到了00000001,使得一位的数目是1。但是,如果我运行以下代码:

代码语言:javascript
复制
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

1位数=8位

为什么我得到的是8而不是1?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-01-31 21:16:49

二的补码表示是关于负数的。正数的补表示是正数本身。

例如,Integer.bitCount(-1)返回32,因为两个-1的补码表示是一个包含所有1s的值(其中32个表示int)。

但是255不是负数,因此它的两个补码表示是值255本身(它的表示中有8个1s )。

票数 19
EN

Stack Overflow用户

发布于 2014-01-31 21:32:42

因为8是11111111的位数。你采取正数的两个补数的步骤是无效的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21490117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档