# Having trouble adding 2 binary numbers in c++

• 11-12-2012
Mizzrym
Having trouble adding 2 binary numbers in c++
I'm having trouble adding 2 binary numbers in C++, instead of having the user input the binary numbers into the array (which I've gotten down) I shortened it to use two predetermined numbers 1010 + 0110, which should total to 10000, but the result I'm getting is 0012FEB0. Could anyone tell me where I'm going wrong with this?
Thanks in advance for any help.

Code:

```#include <iostream> using namespace std; int b2_addition (int a[], int b[]); int main (void) {int a[4]={1,0,1,0}, b[4]={0,1,1,0}, c[8]; b2_addition(a, b); cout<<c; return(0); } int b2_addition (int a[], int b[]) {int c[8], n_bits=4, carry=0;  for(int i=0;i<n_bits;i++)     {int carry=0;     c[i]=a[i]+b[i]+carry;         if(c[i]==3)         {c[i]=1; carry=1;}         if(c[i]==2)            {c[i]=0; carry=1;}         if(c[i]==1)         {c[i]=1; carry=0;}         if(c[i]==0)         {c[i]=0; carry=0;}     } if(carry==1) {n_bits++; c[n_bits]=1;}     return(c[8]); }```
• 11-12-2012
Mizzrym
ok I've found one mistake looking at this in the bottom of the sub routine
Code:

```if(carry==1) {n_bits++; c[n_bits]=1;```
should be
Code:

```if(carry==1) {n_bits++; c[n_bits-1]=1;```
because the array starts at 0 not 1, but I'm still coming up with the same result for the total.....
• 11-12-2012
whiteflags
I would make a new function with the following parameters at a minimum.

void b2_addition (int *c, int *a, int *b);

You will add binary numbers in the normal fashion, but store the answer in c. Use your knowledge of arrays to carry you through.

There is no problem returning an integer exactly, but you will have to correctly copy the answer you would get into an integer variable, by say, moving 1s into the correct place with bitwise operators. I view storing the answer in an array as consistent with how you want to use the function, though.