【问题标题】:Unsigned Binary Subtraction ( 0011 - 1111 = 0100 ?)无符号二进制减法( 0011 - 1111 = 0100 ?)
【发布时间】:2016-01-03 20:57:13
【问题描述】:

我目前正在为大学的一个项目构建一个 4 位按位加减法器,但减法对我来说并不完全有意义。我让它为正值工作1100 - 0100 = 1000 但我不确定当结果是否定时我的答案是否正确。从标题中可以看出,当我为无符号减法执行0011 - 1111 时,我的结果是0100。有人可以向我验证这是正确的答案,并且在执行此计算时溢出或进位都不应该是1

【问题讨论】:

  • 如果我的答案正确,如果您单击我的答案旁边的勾号(左上角)向其他人显示该问题已得到充分回答并让问题的作者(我)知道,我将不胜感激他们的答案是正确的

标签: binary subtraction twos-complement


【解决方案1】:

嗯,简短的回答是否定的。由于您正在使用无符号二进制文件0100 等效于4。如果您采用返回结果的模数,可能会起作用。为此,您可以这样做

public class Modul {
    public static void main(String[] args) {
        int x = 0b0011;
        int y = 0b1111;
        int z = x - y;
        int s1 = Integer.MAX_VALUE+1;
        int s2 = s1*2;
        int finalInt = s2-z;

        System.out.println(x + "+" + y + "=" + z);

        System.out.println(Integer.toBinaryString(x) + "-" + Integer.toBinaryString(y) + "=" + Integer.toBinaryString(finalInt));
    }
}

这将返回1100,相当于12

我不知道你为什么要标记二进制补码,因为你使用的是无符号二进制但是如果你想要二进制补码,你可以使用这个小程序,它会返回一个 32 位有符号二进制数

public class Test {
    public static void main(String[] args) {
        int x = 0b0011;
        int y = 0b1111;
        int z = x - y;

        System.out.println(x + "+" + y + "=" + z);
        //3-15=-12

        System.out.println(Integer.toBinaryString(x) + "-" + Integer.toBinaryString(y) + "=" + Integer.toBinaryString(z));
        //0011-1111=11111111111111111111111111110100
    }
}

我相信这个字符串的最后四位是你得到0100的地方

【讨论】:

    猜你喜欢
    • 2019-02-23
    • 2013-10-03
    • 2011-08-04
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多