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

时间:2016-04-08 02:48:23

标签: java binary

我正在修改用于将二进制文件增加一的代码。我决定最简单的方法是从一个中减去二进制。我只是不知道如何修改它。我主要工作,但当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 个答案:

答案 0 :(得分:0)

如果你想要懒惰,请使用你用来添加一个的相同代码,而是添加two's complement的1。