Adding binary numbers in C++

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); 
}

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;
    }

Since you were asking about C++, you deserve a C++ answer. Use bitsets:

#include <bitset>
#include <iostream>

int main() {
  std::bitset<5> const a("1001");
  std::bitset<5> const b("1111");
  // m here is a mask to extract the lsb of a bitset.
  std::bitset<5> const m("1");
  std::bitset<5> result;
  for (auto i = 0; i < result.size(); ++i) {
    std::bitset<5> const diff(((a >> i)&m).to_ullong() + ((b >> i)&m).to_ullong() + (result >> i).to_ullong());
    result ^= (diff ^ (result >> i)) << i;
  }
  std::cout << result << std::endl;
}

This works for arbitrarily long bit sets.


There is a bug :

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

Also u might want to print in reverse

for(int j=6; j>=0; j--)  
{  
   cout<<result[j]<<" ";  
}

Tags:

C++

Binary

Add