简体   繁体   中英

Adding binary numbers in C++

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

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

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

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

Your arrays are one item too small for your indexing.

int a[3] only has 3 elements, so a[3] = 1 is invalid (it has undefined behaviour ) since it's accessing the 4th element, which doesn't exist.
Likewise for the other arrays.

That means that the whole program has undefined behaviour, ie it can do anything or nothing at all.

(What's probably happening in your case is that writing outside the arrays is overwriting the other variables.)

You're also not initialising the result array, so its content is just some random data.
Since you only update 4 of its elements but print all of them (and more), the output will be random data as well.

Following were the errors in your code and fixed code is also below"

  1. int a[] was of size 3 so it cannot store at the 3rd index. use int a[4].
  2. if(a[i]+b[i]+carry==1) wrong values were assigned in this check update result[i]=1; carry=0.
  3. The sequence of checks is reversed.
  4. The last carry was not stored in the result.
  5. The addition result stored in the result array was in reverse order so printed it in reverse.

here is the working piece of code:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int a[4];
    int b[4];
    int carry=0;
    int result[5];


    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<4; i++)
    {

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


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

    }
    cout<<endl;

        return 0;
}
#include <stdio.h>



int main()

{



    long binary1, binary2;

    int i = 0, remainder = 0, sum[20];



    printf("Enter the first binary number: ");

    scanf("%ld", &binary1);

    printf("Enter the second binary number: ");

    scanf("%ld", &binary2);

    while (binary1 != 0 || binary2 != 0)

    {

        sum[i++] =(binary1 % 10 + binary2 % 10 + remainder) % 2;

        remainder =(binary1 % 10 + binary2 % 10 + remainder) / 2;

        binary1 = binary1 / 10;

        binary2 = binary2 / 10;

    }

    if (remainder != 0)

        sum[i++] = remainder;

    --i;

    printf("Sum of two binary numbers: ");

    while (i >= 0)

        printf("%d", sum[i--]);

    getch();
    return 0;

}

Repeatedly do

(x, y) <- ((x & y) << 1, x ^ y)

until x is 0. y is the answer.

you should do this

for(int i = 3; i >= 0; i--)
    {
        if(a[i] + b[i] + carry == 0)
        {
            result[i] = 0;
            carry = 0;
        }
        else if(a[i]+b[i]+carry==1)
        {
            result[i]=1;
            carry=0;  
        }
        else if(a[i] + b[i] + carry == 2)
        {
            result[i] = 0;
            carry = 1;
        }
        else if(a[i] + b[i] + carry > 2)
        {
            result[i] = 1;
            carry = 1;
        }
        printf("%d",result[i]);
    }

A non-conventional solution, but it works:

int main() {

  int A[] = { 0, 0, 0, 1, 1, 0, 1, 0};
  int B[] = { 0, 0, 0, 0, 1, 1, 0, 0};

  int size = sizeof(A)/sizeof(*A);

  int C[size+1];
  int t = 0;

  for(int i = size-1; i > -1; i--){

      C[i+1] = A[i]+B[i]+t;
      t = C[i+1]/2;
      C[i+1] %= 2;
  }

  C[0] = t;
}

What if their sizes are not the same? Also, you would want to allow the user to input the binary numbers (in this case representing integers) as integers and not as elements of arrays. Here is a piece of code that accomplishes those :-)

#include <iostream>
using namespace std; 

// Add two numbers in binary

void sumBinary(int num1, int num2, int* sum12){
    int mod1 = 0;
    int mod2 = 0;
    int carry = 0;
    int factor = 1;

    int flag = 0;

    *sum12 = 0;

    while (!flag){
        mod1 = num1 % 10;
        mod2 = num2 % 10;

        num1 /= 10;
        num2 /= 10;
        if ((carry + mod1 + mod2) == 2){
            *sum12 += 0;
            carry = 1;
        }
        else if ((carry + mod1 + mod2) == 3){
            *sum12 += factor;
            carry = 1;
        }
        else if ((carry + mod1 + mod2) == 0){
            *sum12 += 0;
            carry = 0;
        }
        else{
            *sum12 += factor;
            carry = 0;
        }
        factor *= 10;
        if ((num1 == 0) && (num2 == 0)){ 
            *sum12 += carry*factor;
            flag = 1; }


    }
}
void main(){
    int num1, num2, sum12;

    cout << "Enter the first binary integer number: ";
    cin >> num1;
    cout << "Enter the second binary integer number: ";
    cin >> num2;

    sumBinary(num1, num2, &sum12);

    cout << "The sum in binary form is :" << sum12 << endl;
}

A simple way :

    int getBit(string s, int index)
    {
         if(index >= 0)   return (s[index] - '0');
         else             return 0;
    }

    string addBinary(string a, string b) 
    {
        if(a.size() > b.size())        while(a.size() > b.size()) b = "0" + b;
        else if(b.size() > a.size())   while(b.size() > a.size()) a = "0" + a;

        int l = max(a.size()-1, b.size() - 1);

        string result = ""; 
        int s=0;        

        while(l>=0 || s==1)
        {
            s += getBit(a, l) + getBit(b, l) ;
            result = char(s % 2 + '0') + result;
            s /= 2;
            l--;
        }
        return result;
    }
int main(){
     ios::sync_with_stdio(0); cin.tie(0);

     int num1=12, num2=45, sum=0;
     bool b1, b2, carry=0;


     for(int i=0;i<32;i++){

        b1=( 1<<i ) & num1;
        b2=( 1<<i ) & num2;

        sum = (b1 ^ b2 ^ carry) ? sum ^ (1<<i) : sum; 

        carry = ((b1 & b2) | (b1 & carry) | (b2 & carry));

     }

    cout<<sum;

    return 0;
}

Easy to understand code
Add Two Binary Numbers (input datatype = int)

#include <iostream>
using namespace std;

int power(int a, int b)
{
    int ans = 1;
    while (b)
    {
        ans *= a;
        b--;
    }
    return ans;
}

int main()
{
    int n1, n2, carry = 0, ans = 0, rem1, rem2, remsum = 0, i;
    cout << "Enter First Number : ";
    cin >> n1;
    cout << "Enter Second Number : ";
    cin >> n2;

    for (i = 0; n1 != 0 || n2 != 0; i++, n1 /= 10, n2 /= 10)
    {
        rem1 = n1 % 10;
        rem2 = n2 % 10;
        remsum = rem1 + rem2 + carry;
        if (remsum == 2)
        {
            carry = 1;
            remsum = 0;
        }
        else if (remsum == 3)
        {
            carry = 1;
            remsum = 1;
        }
        else if (remsum == 0)
        {
            carry = 0;
            remsum = 0;
        }
        else if (remsum == 1)
        {
            carry = 0;
            remsum = 1;
        }
        ans = remsum * power(10, i) + ans;
    }

    ans = carry * power(10, i) + ans;

    cout << ans;

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM