In: Computer Science
Write a C++ program to perform two-4 bit binary number operations including addition and subtraction. The user will type in two-4 bit binary numbers with the selection of one of the operations. Then, the program will calculate the result of the calculation. Display two-4 bit binary numbers and the result from the calculation.
Program for finding summation of two binary values
Algorithm
1. Initialize two binary numbers as input numbers.
2. Add each bits from the two binary numbers bit wise from right
most location.
Program/Source Code
#include <stdio.h>
int main()
{
long binary1, binary2;
int i = 0, remainder = 0, sum[20];
printf("Enter the first binary number: ");
scanf("%ld", &binary1);
printf("Enter the second binary number: ");
scanf("%ld", &binary2);
binary1=abs(binary1); //will convert negative values into positive
values.
binary2=abs(binary2); //will convert negative values into positve
values.
while (binary1 != 0 || binary2 != 0)
{
sum[i++] =(binary1 % 10 + binary2 % 10 + remainder) % 2;
remainder =(binary1 % 10 + binary2 % 10 + remainder) / 2;
binary1 = binary1 / 10;
binary2 = binary2 / 10;
}
if (remainder != 0)
sum[i++] = remainder;
--i;
printf("Sum of two binary numbers: ");
while (i >= 0)
printf("%d", sum[i--]);
return 0;
}
This solution can be improved by checking that entered number is positive or negative. In case of negative numbers 2's complement can be taken before addition because in case of addition substraction A-B = A+(-B) and so on.