Need help with binary substraction

Keeponfalling 41 Reputation points
2020-12-15T13:44:54.637+00:00

I have two given strings (as binary numbers) and I want to change my code to make a subtraction. The problem is that I don't know how to manage the borrow 1 after one loop. Thanks!

while (i >= 0 || j >= 0)
            {
                byte a = (byte)(storeBinaryNumber[i] - '0');
                byte b = (byte)(secondNumber[j] - '0');
                int c = a - b;
                if (c < 0)
                {
                    result = '1' + result;
                }
                else
                {
                    result += '0';
                }

                i--;
                j--;
            }
Developer technologies C++
0 comments No comments
{count} votes

Accepted answer
  1. Barry Schwarz 3,746 Reputation points
    2020-12-15T17:15:33.637+00:00

    Your code fails to distinguish between 1-1 and 1-0. Both result in a non-negative c but you append a '0' to result when the latter case requires a '1' be prepended.

    Furthermore, you prepend '1' but append '0'. New characters should always be added on the same end of result. Since you are processing characters from right to left, you should prepend '0' the same way you do '1'.

    If both values have the same length, you don't need to test i and j. Either one is sufficient. If not, you may need to extend the shorter one.

    It would be much easier to to compute the twos-complement of the subtrahend (secondNumber) and then perform addition. Carries are easier to deal with than borrows.

    If you need to do actual subtraction, then you need a borrow flag that starts as false.. Each time you extract a, test the flag. When true, reset it to false and decrement a (yes, it may go negative). if c<0, c+=2 and set the flag to true. In all cases, add the character (c+'0') to result.


1 additional answer

Sort by: Most helpful
  1. Keeponfalling 41 Reputation points
    2020-12-16T07:27:44.607+00:00

    Ok, thank you for your help make sense now.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.