【问题标题】:how to convert twos complement binary string to negative decimal number?如何将二进制补码字符串转换为负十进制数?
【发布时间】:2016-08-31 17:06:16
【问题描述】:

我正在尝试找到一种快速/简单的方法将二进制补码二进制字符串转换为负十进制数。我尝试使用this question 中介绍的方法,但它不起作用。这是我要运行的代码:

short res = (short)Integer.parseInt("1001", 2);
System.out.println(res);

当我运行这段代码时,结果是 9。 我错过了什么吗? 我做错了什么?

【问题讨论】:

  • 你没有应用任何逻辑来判断这个代码的二进制补码是什么。你知道为什么它是一个负数。您将不得不分解您尝试解析的数字并为其添加更多逻辑。不只是将其从二进制转换为十进制。
  • 我应该应用什么逻辑?如果我的二进制字符串以“1”开头,我将它解码为负数。
  • 如果我的原始数字是 7--> 111,如果我想表示 -7,它的二进制形式将是 1001。我想要的只是将 '1001' 解码为 -7。

标签: java binary twos-complement negative-number


【解决方案1】:

Two's Complement algorithm,之后,我写了以下内容:

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;
}

以下是一些示例运行:

运行:
二进制补码:1000:-8
二进制补码:1001:-7
二进制补码:1010:-6
二进制补码:0000:0
二进制补码:0001:1
二进制补码:0111:7

【讨论】:

  • 有相同的想法,只是略有不同。先变为十进制,然后减 1,然后变为二进制并翻转位,然后再次变为十进制乘以 -1。
  • 似乎当 binaryInt ="10000000000000000000000000000000" 时,decimalValue + 1 会溢出。但是当我测试该函数时,它会返回正确的结果。你能告诉我为什么会这样吗?
【解决方案2】:

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

应该如此。

我错过了什么吗?我做错了什么?

您的代码与您引用的答案之间的区别在于输入中的位数。如果不指定宽度,则“双补码”的定义不明确。您复制的答案是 16 位二进制补码,因为 Java shorts 是 16 位宽。如果您想要 4 位二进制补码,则没有对应的 Java 数据类型,因此您将无法采用相同的捷径。

【讨论】:

  • 好的,谢谢。使用“快捷方式”可以转换哪些长度?
  • 这看起来像是一个硬件分配。为什么要走捷径?并不是说它们不好,而是因为我确定您的教授希望看到您使用逻辑来解析数字。
  • @DanyLavrov,补充练习真是个好主意!我很佩服你的动力!
  • @robotlos 足够接近,我实际上是 33 岁,我只是需要它来工作。只是不想写我认为已经存在的东西。想通了,谢谢大家的帮助。
猜你喜欢
  • 2016-07-16
  • 2021-05-16
  • 1970-01-01
  • 2013-09-28
  • 1970-01-01
  • 2012-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多