Search code examples
c++binarycalculatorsubtraction

Binary Calculator subtraction


I am currently doing a project for my school which is about Binary Numbers. I have already made an addition Calculator which works fine and now I'm trying to make one for subtraction. There I'm facing some problems. The biggest one is that I get negative numbers as output and when I use the binary 2's complement I don't get any negative results but they are still wrong. Example: When substracting 110010(50) with 11110(30) my output is 10-1-100 instead of 10100. When transforming 30 in 2nd complement (00010) my output is 110000 which is 48 in decimal

Here is the code:

#include <iostream>
using namespace std;
int main() {
    long a, b;
    int i = 0, r = 0, sub[20];
    cout << "1st number: ";
    cin >> a;
    cout << "2nd number: ";
    cin >> b;
    while (a != 0 || b != 0)
    {
        sub[i++] = (a % 10 - b % 10 + r) % 2;
        r = (a % 10 - b % 10 + r) / 2;
        a = a / 10;
        b = b / 10;
    }
    if (r != 0)
        sub[i++] = r;
    --i;
    cout << "Difference: ";
    while (i >= 0)
        cout << sub[i--];
    cout << ". ";


    system("pause");
    return 0;
}

Thanks in advance


Solution

  • About the subtraction, I can see that you're only comparing the numbers bit by bit, and if one of the bits in the 1st number is 0 and the corresponding bit in the 2nd number is 1, it will just do 0 - 1 = -1, without considering the other digits of the number.

    Adding a condition that changes the other numbers when the current number is negative should solve the problem:

    #include <iostream>
    using namespace std;
    
    int main() {
        long a, b;
        int i = 0, r = 0, sub[20];
        cout << "1st number: ";
        cin >> a;
        cout << "2nd number: ";
        cin >> b;
        while (a != 0 || b != 0)
        {
            sub[i] = (a % 10 - b % 10 + r) % 2; //Change the "i++" and put "i".
            r = (a % 10 - b % 10 + r) / 2;
            //Add this:
            while(sub[i - 1] < 0)
            {
                sub[i-1] += 2;
                sub[i]--;
            }
            //Until here
            a = a / 10;
            b = b / 10;
            i++; //Increment "i" here.
        }
        if (r != 0)
            sub[i++] = r;
        --i;
        //Add this if you want to ignore the leading 0's:
        while (i >= 1 && sub[i] == 0)
            i--;
        //Until here.
        cout << "Difference: ";
        while (i >= 0)
            cout << sub[i--];
        cout << ". ";
    
    
        system("pause");
        return 0;
    }
    

    About transforming numbers in 2nd complement. How the input is supposed to be?