In this program, addition of the entered number was performed. The
entered number may be signed or unsigned (positive or negative). After
the addition, the output was displayed in the binary as well as in
decimal.
/** //By: www.subirank.com (Suresh Ghatuwa) //Binary Addition Using C Program */ #include<stdio.h> #include<conio.h> #include<math.h> //Input the data function int get() { int flag=0; int a; do {
printf("ENTER VALUE: "); scanf("%d",&a); if(a< 0) { a = a * -1; // changing the negative value into positive flag = 1; } if(a>16) // limiting input value to 16 printf("\n\t!INVALID NUMBER.ENTER VALUE (-16 < A < 16)!"); }while(a>16); if(flag) a = a *-1; return(a); } //binary addition void add(int *a,int *b,int n) { int i,j,carry=0; j=n-1; for(i=n-1;i>=0;i--) { if (a[i]==1 && b[i]==1 && carry ==1) { a[j] = 1; carry =1; } else if (a[i]==1 && b[i]==1 && carry ==0) { a[j]=0; carry=1; } else if (a[i]==0 && b[i]==1 && carry ==0) { a[j]=1; carry=0; } else if (a[i]==0 && b[i]==1 && carry ==1) { a[j]=0; carry=1; } else if (a[i]==1 && b[i]==0 && carry ==1) { a[j]=0; carry=1; } else if (a[i]==1 && b[i]==0 && carry ==0) { a[j]=1; carry=0; } else if (a[i]==0 && b[i]==0 && carry ==1) { a[j]=1; carry=0; } else if (a[i]==0 && b[i]==0 && carry ==0) { a[j]=0; carry=0; } j--; } } //Decinal to Binary Conversion void binary(int x,int*arr,int n) { int i,p=x,c[8]; c[0]=0; c[1]=0; c[2]=0; c[3]=0; c[4]=0; c[5]=0; c[6]=0; c[7]=1; for(i=0;i<n;i++) arr[i] = 0; if(x < 0) x = x * -1; i = n-1; do { arr[i]=x%2; x = x/2; i--; }while(x!=0); if(p< 0) { for(i=0;i< n;i++) { arr[i]=1-arr[i]; } add(arr,c,n); printf("\n"); } printf("\n\nTHE BINARY EQUIVALENT OF %d IS : ",p); for(i=0;i<n;i++) printf("%d",arr[i]); } void main() { int i,j,a,b; int s=0,z=0,Q[8],M[8],A[8]={0,0,0,0,0,0,0,1},n=0; int p; clrscr(); printf("\t\t\tBinary Addition Using C Program\n"); printf("--------------------------------------------------\n"); a = get(); // input the value a b=get(); //input the value b n=8; printf("---------------------------------------------------\n"); binary(a,M,n); //converting the input value a into its binary binary(b,Q,n); //converting the input value b into its binary printf("\n\n---------------------------------------------------\n"); add(M,Q,n); printf("\n"); printf("The answer in Binary is: "); for(i=0;i<n;i++) { printf("%d",M[i]); } if((a<0 || b<0) && (b<a)) { for(i=0;i<n;i++) { M[i] = 1-M[i]; } add(M,A,n); } for(i=n-1;i>=0;i--) { s = s + (pow(2,z) * M[i]); z = z+1; } if((a<0 || b<0)&&(b<a)) { printf("\nThe answer in decimal is: -%d",s); } else { printf("\nThe answer in decimal is: %d",s); } getch(); }
No comments:
Post a Comment