In this article, we are going to learn How to find Binary Addition and Subtraction in C two numbers with examples.
C Program to find bnary addition two numbers
In this example, we are taking two input numbers from the user and defining a function that finds the addition of two binary numbers. We are passing these numbers to this function and return the result.
#include <stdio.h>
int BinaryAddition(int num1,int num2);
int main()
{
int num1,num2;
int Result;
printf("Please enter the First Number: ");
scanf("%d",&num1);
printf("Please enter the Second Number: ");
scanf("%d",&num2);
Result = BinaryAddition(num1,num2);
printf("The Binary Addition of given Numbers is: %d\n",Result);
return 0;
}
int BinaryAddition(int num1,int num2)
{
int c;
while (num2 != 0)
{
//Calculate carry and perform left shift
c = (num1 & num2) << 1;
num1 = num1^num2;
num2 = c;
}
return num1;
}
Output
Please enter the First Number: 5
Please enter the Second Number: 5
The Binary Addition of given Numbers is: 10
C Program to find bnary substraction of binary two numbers
In this example, we are taking two input numbers from the user and defining a function that finds the subtraction of two binary numbers. We are passing these numbers to this function and return the result.
#include <stdio.h>
int BinarySubtraction(int num1,int num2);
int BinaryAddition(int num1,int num2)
{
int c;
while (num2 != 0)
{
//Calculate carry and perform left shift
c = (num1 & num2) << 1;
num1 = num1^num2;
num2 = c;
}
return num1;
}
int main()
{
int num1,num2;
int Result;
printf("Please enter the First Number: ");
scanf("%d",&num1);
printf("Please enter the Second Number: ");
scanf("%d",&num2);
Result = BinarySubtraction(num1,num2);
printf("The Binary Subtraction of given Numbers is: %d\n",Result);
return 0;
}
int BinarySubtraction(int num1,int num2)
{
int c;
num2 = BinaryAddition(~num2, 1);
while (num2 != 0)
{
//Calculate carry and perform left shift
c = (num1 & num2) << 1;
num1 = num1 ^ num2;
num2 = c;
}
return num1;
}
Output
Please enter the First Number: 23
Please enter the Second Number: 7
The Binary Subtraction of given Numbers is: 16