Home >>c programs >C Program to find Binary Addition and Binary Subtraction

C Program to find Binary Addition and Binary Subtraction

C Program to find Binary Addition and Binary Subtraction

In this example, we will see a C program through which we can do the addition and subtraction of the binary numbers.

Binary addition or subtraction is similar to the regular addition or subtraction, but in binary addition or subtraction we have only two digits that are 0 and 1.

Program:

#include <stdio.h>
//function for Binary Addition
int binAddition(int a,int b) 
{
int c; //carry
while (b != 0) {
//find carry and shift it left
c = (a & b) << 1;
//find the sum
a=a^b;
b=c;
}
return a; 
}
//function for Binary Subtraction
int binSubtracton(int a, int b) 
{
int carry;
//get 2's compliment of b and add in a
b = binAddition(~b, 1);
while (b != 0) {
//find carry and shift it left    
carry = (a & b) << 1;
//find the sum
a = a ^ b;
b = carry;
}
return a;
}
int main() 
{
int number1,number2, binAdd, binSub;
printf("Input first integer value: ");
scanf("%d",&number1);
printf("Input second integer value: ");
scanf("%d",&number2);
binAdd=binAddition(number1,number2);
binSub=binSubtracton(number1,number2);
printf("Binary Addition: %d\n",binAdd);
printf("Binary Subtraction: %d\n",binSub);
return 0;
}

Output:
Input first integer value: 83
Input second integer value: 37
Binary Addition: 120
Binary Subtraction: 46