I need a program in C, where I can do subtraction of BINARY numbers, for example
ID: 3891201 • Letter: I
Question
I need a program in C, where I can do subtraction of BINARY numbers, for example "11-10 = 01".
And how can I join this program(Addition binary) with the subtraction program? (NO C ++, and not C ++ libraries, only in C language, please).
#include <stdio.h>
#include <math.h>
int main() {
int bin1, bin2;
int temp1, temp2;
int max, min, carry = 0, sum = 0,mid, po=1;
printf("Enter binary number 1:");
scanf("%d", &bin1);
printf("Enter binary number 2:");
scanf("%d", &bin2);
if(bin1>bin2)
{
max = bin1;
min = bin2;
}
else
{
max = bin2;
min = bin1;
}
while(max>0)
{
temp1 = max%10;
max = max/10;
temp2 = min%10;
min = min/10;
mid = (temp1 + temp2 + carry)%2;
carry = (temp1 + temp2 + carry)/2;
sum = po*mid + sum;
po = po*10;
if ( max == 0 && carry >0)
{
sum = po*carry + sum;
}
}
printf("Binary addition = %d", sum);
return 0;
}
Explanation / Answer
/* here I have modified your code where it will perform subtraction & addition
*/
#include <stdio.h>
#include <math.h>
int main() {
int bin1, bin2;
int temp1, temp2;
//2 variables borrow & diff are added & reutilising mid variable
int max, min, carry = 0, sum = 0,mid, po=1, borrow=0, diff=0;
printf("Enter binary number 1:");
scanf("%d", &bin1);
printf("Enter binary number 2:");
scanf("%d", &bin2);
if(bin1>bin2)
{
max = bin1;
min = bin2;
}
else
{
max = bin2;
min = bin1;
}
while(max>0)
{
temp1 = max%10;
max = max/10;
temp2 = min%10;
min = min/10;
mid = (temp1 + temp2 + carry)%2;
carry = (temp1 + temp2 + carry)/2;
sum = po*mid + sum;
//subtraction code starts here
mid = (temp1 - temp2 - borrow)%2; // find difference
borrow = (temp1 - temp2 - borrow)/2; //find borrow
diff = po*mid + diff; //difference value as per binay value
po = po*10;
if ( max == 0 && carry >0)
{
sum = po*carry + sum;
}
//if there is borrow remainded then add to final diff value
if ( max == 0 && borrow >0)
{
diff = po*borrow + diff;
}
}
printf("Binary addition = %d ", sum);
//print final subtracted value
printf(" Binary subtraction = %d", diff);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.