Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding binary numbers in C++

Tags:

c++

add

binary

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");
}
like image 274
Muhammad Arslan Jamshaid Avatar asked Nov 08 '12 05:11

Muhammad Arslan Jamshaid


2 Answers

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); 
}
like image 141
krammer Avatar answered Sep 21 '22 12:09

krammer


You could use "Bitwise OR" operation to reduce the code since

1 or 1 = 1
1 or 0 = 1
0 or 1 = 1
0 or 0 = 0

You could also convert both number to decimal sum and them go back to binary again.

Converting decimal to binary

int toBinary (unsigned int num, char b[32])
    {
    unsigned  int x = INT_MIN;      // (32bits)
    int i = 0, count = 0;
    while (x != 0)
    {
      if(x & num) // If the actual o bit is 1 & 1 = 1 otherwise = 0
      {
          b[i] = '1';
          count++;
      }
      else b[i] = '0';

      x >>=1;       // pass to the left
      i++;          
    }
    return count;
    }
like image 35
dreamcrash Avatar answered Sep 20 '22 12:09

dreamcrash