In: Computer Science
c++
Create a program where you can add binary while they're still in binary form and convert them to decimal, adds them, then converts then back to binary. (without built in conversions).
Convert 34 to Binary Convert 22 to Binary Convert 1001 to Decimal Convert 111011 to Decimal Add 11 and 1110 in Binary Return the Answer in Binary Subtract 111 from 1010 in Binary, then Convert the Answer to Decimal
#include <iostream>
using namespace std;
int toDecimal(long n)
{
long num = n;
int decimalNum =0;
int remaind;
int base =1;
while (num > 0)
{
remaind = num % 10;
decimalNum = decimalNum + remaind * base;
num = num / 10 ;
base = base * 2;
}
return decimalNum;
}
long toBinary(int n)
{
int num = n;
long binaryNum = 0;
int remaind, i = 1;
while (num!=0)
{
remaind = num%2;
num = num/2;
binaryNum = binaryNum + remaind*i;
i = i * 10;
}
return binaryNum;
}
int main()
{
long binary1 = 101010;
long binary2 = 111111;
cout<<"Calculating sum of two binary Numbers
"<<endl;
int sum = toDecimal(binary1)+toDecimal(binary2);
cout<<"Sum of two binary numbers in Decimal is :
"<<sum<<endl;
long sumBinary = toBinary(sum);
cout<<"Sum of two binary numbers in Binary is :
"<<sumBinary<<endl;
return 0;
}
Output
Calculating sum of two binary Numbers Sum of two binary numbers in Decimal is : 105 Sum of two binary numbers in Binary is : 1101001
Screenshot
Feel free to ask any doubts, if you face any difficulty in understanding.
Please upvote the answer if you find it helpful