Logic incorrect for adding binary

I have to sum two numbers with binary addition and store the value in an array using a function. I am not getting the right answer however. I either get all 0's or a few random 1's that aren't in the right place. (Couldn't figure out how to make an array all of 1 number either)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
  #include <stdio.h>
void bin_add ( unsigned int x, unsigned int y, char binsum[32]);
int main()
{
    char binsum[32]={'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0',};
    int val1, val2, m=31;
    printf("Enter 2 values. They will be binary summed\n");
    scanf("%d%d", &val1, &val2);
    bin_add(val1, val2, binsum);
    for(; m>0; m--)
    {
        printf("%c", binsum[m]);
    }
    return 0;
}
void bin_add ( unsigned int x, unsigned int y, char binsum[32] )
{
    int xarray[32], yarray[32];
    int i=0, j=0, k=0, storex, storey;
    while(x>0)
    {
        storex = x%2;
        if(storex==0)
        {
            xarray[i]=0;
        }
        else
        {
            xarray[i]=1;
        }
        x = x/2;
        i++;
    }
    while(y>0)
    {
        storey = y%2;
        if(storey==0)
        {
            yarray[j]=0;
        }
        else
        {
            yarray[j]=1;
        }
        y = y/2;
        j++;
    }
    for(k=0; k<=31; k++)
    {
        int carry;
        int compare = xarray[k]+yarray[k]+carry;
        carry =0;
        if(compare==1)
        binsum[k] = '1';
        else if(compare==2)
        {
        binsum[k] = '0';
        carry=1;
        }
        else if(compare==3)
        {
        binsum[k]= '1';
        carry =1;
        }
        else
        binsum[k]='0';
    }
}.
The first thing that is wrong is line 50.
int carry;
This variable in uninitialized, so will have random data in it.
Move it outside the loop of line 48, and initialise it to zero:
int carry=0;

See if that helps.
Last edited on
Yep that was the problem. that and the loop was missing an iteration. should be m>=0

Thank you!
There are some "improvements" that would look good, and give greater clarity:

(1) lines 20-33 and 34-47 are essentially identical, and can be made into a single function, with two calls to it, returning the array[32].

(2) The constants 32 (lines 5,18,18) and 31 (line 6) are related. To have it defined once is much better and more maintainable.

(3) The function bin_add does more than it's name suggests. It converts to binary as well. Better to separate this out with the correct name.
Topic archived. No new replies allowed.