Mila
Mila

Reputation: 11

Algorithm for subtraction of binary numbers

I am doing a project in C++ and I'm having hard time with substraction of binary numbers. It's easy doing it on paper but in code it's a bit hard for me. Can someone please give me the algorithm for the subtraction of two binary numbers? It's supposed to be done WITHOUT conversion to the decimal system. Thanks!

Upvotes: 1

Views: 2170

Answers (1)

Giacomo
Giacomo

Reputation: 571

int subtractBinaries(int x, int y) {
    while (y != 0) {
        int borrow = (~x) & y;
        x = x ^ y;
        y = borrow << 1;
    }
    return x;
}

Upvotes: 2

Related Questions