Binary Addition in C

This is a dynamic program which accepts two integer from the console and convert them to Binary Numbers.
After converting them, they are added and the result is then displayed in the console !

Binary addition is highly necessary because computer only understands the addition. 
Whether in case of  multiplication it’s repetitive addition, in case of  division it is repetitive division and for subtraction it is the addition of the two’s compliment of the other number.
Screenshots [DEMO]

The Code:

#include<stdio.h>
#include<malloc.h>
int *q,*m,*c,n,d,siz;
int powr(int x,int y)
{
int s=1,i;
for(i=0;i<y;i++)
s=s*x;
return s;
}
void bin(int n, int arr[]){
int r, i = 0;
do{
r = n % 2;
n /= 2;
arr[i] = r;
i++;
}while(n > 0);
}
void set(int array[], int x){
int i,tmp[20]={0};
for(i = x -1; i >=0; i--)
tmp[x-1-i]=array[i];
for(i=0;i<x;i++)
array[i]=tmp[i];
}
int len(int x)
{
int i=0;
while(powr(2,i)<=x) i++;
return ++i;
}
void print(int arr[],int n)
{
int i;
for(i=0;i<n;i++)
printf("%d ",arr[i]);
}
void addBinary(int a1[], int a2[])
{
int bi[2]={0},ca[20]={0};
int t=siz,tmp=0;
int *su=(int*)malloc(sizeof(int)*siz);
while(t-->0)
{
tmp=a1[t]+a2[t]+ca[t];
bin(tmp,bi);
su[t]=bi[0];
ca[t-1]=bi[1];
bi[0]=0;bi[1]=0;
}
for(t=0;t<siz;t++)
a1[t]=su[t];
free(su);
}
int main()
{
printf("Enter two numbers a,b : ");
scanf("%d,%d",&n,&d);
siz=n>d?n:d;
siz=len(siz)-1;
q=(int*)malloc(sizeof(int)*siz);
bin(n,q);
m=(int*)malloc(sizeof(int)*siz);
bin(d,m);
set(q,siz);
set(m,siz);
addBinary(q,m);
print(q,siz);
return 0;
}

Found Bugs ?
Feel Free to report us !

Related posts

Leave a Comment