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