【问题标题】:Way to get the twos compliment decimal from binary?从二进制中获取二进制补码十进制的方法?
【发布时间】:2021-12-14 02:56:43
【问题描述】:

我有一个简单的问题,我如何得到二进制的恭维而不是二进制的常规答案?我有一个执行展位算法的程序,但是当它返回小数时,它给了我一个有点太高的数字,我正在做 9 * -9,它给出的答案是 65455。我只想知道是否有一种获得两个恭维的方法(-81)。我从代码中得到的二进制文件是 1111111110101111,我通过环顾四周知道在找到两者的恭维时等于 -81,我只是不知道如何让我的程序识别或说出来。

编辑:我找到了一个小修复,基本上只是检查产品的二进制文件是否等于我得到的结果,这就是我打印二进制文件并将其转换为十进制的方式,将打印区域作为回答说必须在这里做点什么,我让它正常工作但如果可以的话想清理它

public static void main(String args[]){
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the first number: ");
    int operand1 = sc.nextInt();
    System.out.print("Enter the second number: ");
    int operand2 = sc.nextInt();
    String answer = multiply(operand1, operand2);
    System.out.println("Final Product (binary): " + answer);
    int decimal=Integer.parseInt(answer,2); 
    if(operand1 * operand2 < 0) {
        int decProduct = operand1 * operand2;
        String biProduct = toBinary(decProduct, 16);
        if (biProduct.length() > 16) 
        {
            biProduct = biProduct.substring(biProduct.length() - 16);
        } 
        if(biProduct.equals(answer)) {
            decimal = decProduct;
        }
    }
    System.out.println("Final Answer (decimal): " + decimal);  
}

【问题讨论】:

  • 当您只有 16 位时,您可以决定其中一位是加号/减号,留下 15 位作为数字,或者您将数字定义为正数并具有全部 16 位。在这种情况下,您不同意 JVM 的处理方式。

标签: java binary twos-complement


【解决方案1】:

计算机不知道这意味着什么。它只是有一些记忆,并且在那个记忆中是位。其中的位是例如1111111110101111.

这个序列是什么意思?谁知道。计算机不知道也不关心。

print 代码决定。 IT 决定将其接收并渲染,以使字符 -81 出现在您的计算机屏幕上。

因此,这里的错误在打印代码中。无需转换。位序列是所有的东西,一次:它是1111111110101111,它是65455,它是-81。显示哪一个取决于您的打印方式。

鉴于您的打印代码不在问题中,您将不得不使用此信息弄清楚。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多