繁体   English   中英

将二进制数减1而不将其转换为整数

[英]Decreasing a binary number by 1 without converting it to an integer

我正在修改我用来增加二进制的代码。 我决定最简单的方法是从一个中减去二进制。 我只是不知道如何修改它。 我主要工作,但是当0从1中减去时,我不确定我应该用我的进位变量做什么。 这就是我所拥有的:

String decB(String b)
{
    String b2 = "0001"; //binary of 1 will be subtracted from the user input binary
    String b3 = ""; //result initialized as empty string
    int i1 = b.length()-1; //start at the end of the first string
    int i2 = b2.length()-1; //start at the end of the second string
    int c = 0; //initialize storage as zero. Prevents negative digits.

    while (i1 >= 0 && i2 >= 0) //while digits are either one or zero
    {
        int difference = ((b.charAt(i1)-'0')-(b2.charAt(i2)-'0')+c); //subtracts the binaries
        c = difference/2; 
        b3 = difference%2 + b3;
        i1--;
        i2--;
    }
    if (c < 0)
        b3 = b3 + c;

    return b3;
}

如果你想要懒惰使用你用来添加一个的相同代码,而是添加两个补码 1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM