首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将两个补二进制字符串转换为负十进制数?

问如何将两个补二进制字符串转换为负十进制数?
EN

Stack Overflow用户
提问于 2016-05-05 19:17:07
回答 2查看 6.9K关注 0票数 1

我正试图找到一种快速/简单的方法,将两个补码二进制字符串转换为一个负十进制数。我尝试过使用这个问题中提供的方法,但它不起作用。这是我试图运行的代码:

代码语言:javascript
复制
short res = (short)Integer.parseInt("1001", 2);
System.out.println(res);

当我运行这段代码时,结果是9,是不是遗漏了什么?我做错什么了?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-05-05 21:48:25

在二补算法,之后,我写了以下内容:

代码语言:javascript
复制
public static int getTwosComplement(String binaryInt) {
    //Check if the number is negative.
    //We know it's negative if it starts with a 1
    if (binaryInt.charAt(0) == '1') {
        //Call our invert digits method
        String invertedInt = invertDigits(binaryInt);
        //Change this to decimal format.
        int decimalValue = Integer.parseInt(invertedInt, 2);
        //Add 1 to the curernt decimal and multiply it by -1
        //because we know it's a negative number
        decimalValue = (decimalValue + 1) * -1;
        //return the final result
        return decimalValue;
    } else {
        //Else we know it's a positive number, so just convert
        //the number to decimal base.
        return Integer.parseInt(binaryInt, 2);
    }
}

public static String invertDigits(String binaryInt) {
    String result = binaryInt;
    result = result.replace("0", " "); //temp replace 0s
    result = result.replace("1", "0"); //replace 1s with 0s
    result = result.replace(" ", "1"); //put the 1s back in
    return result;
}

下面是一些示例运行:

跑: 2的补充数: 1000:-8 二补: 1001:-7 二补: 1010:-6 2的补码: 0000: 0 二补: 0001: 1 二补: 0111: 7

票数 2
EN

Stack Overflow用户

发布于 2016-05-05 19:25:40

当我运行这段代码时,结果是9。

它应该是的。

我是不是遗漏了什么?我做错什么了?

您的代码和您引用的答案之间的区别是输入中的位数。“2‘s补语”没有指定宽度就不能很好地定义。您复制的答案是16位二位的补充,因为Java short是16位宽的。如果您想要4位2的补充,那么就没有相应的Java数据类型,因此您将无法采取相同的快捷方式。

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

https://stackoverflow.com/questions/37058582

复制
相关文章

相似问题

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