Adding binary numbers in C++

Muhammad Arslan Jamshaid picture Muhammad Arslan Jamshaid · Nov 8, 2012 · Viewed 60.9k times · Source

How would I add two binary numbers in C++? What is the correct logic?

Here is my effort, but it doesn't seem to be correct:

#include <iostream>
using namespace std;
int main()
{
    int a[3];
    int b[3];
    int carry = 0;
    int result[7];

    a[0] = 1;
    a[1] = 0;
    a[2] = 0;
    a[3] = 1;

    b[0] = 1;
    b[1] = 1;
    b[2] = 1;
    b[3] = 1;

    for(int i = 0; i <= 3; i++)
    {
        if(a[i] + b[i] + carry == 0)
        {
            result[i] = 0;
            carry = 0;
        }

        if(a[i] + b[i] + carry == 1)
        {
            result[i] = 0;
            carry = 0;
        }

        if(a[i] + b[i] + carry == 2)
        {
            result[i] = 0;
            carry = 1;
        }

        if(a[i] + b[i] + carry > 2)
        {
            result[i] = 1;
            carry = 1;
        }
    }
    for(int j = 0; j <= 7; j++)
    {
        cout<<result[j]<<" ";
    }
    system("pause");
}

Answer

krammer picture krammer · Nov 8, 2012

Well, it is a pretty trivial problem.

How to add two binary numbers in c++. what is the logic of it.

For adding two binary numbers, a and b. You can use the following equations to do so.

sum = a xor b

carry = ab

This is the equation for a Half Adder.

Now to implement this, you may need to understand how a Full Adder works.

sum = a xor b xor c

carry = ab+bc+ca

Since you store your binary numbers in int array, you might want to understand bitwise operation. You can use ^ for XOR,| operator for OR, & operator for AND.

Here is a sample code to calculate the sum.

for(i = 0; i < 8 ; i++){
   sum[i] = ((a[i] ^ b[i]) ^ c); // c is carry
   c = ((a[i] & b[i]) | (a[i] & c)) | (b[i] & c); 
}