In: Computer Science
1. Enhance Binary System Conversion program with Lab05.2 Addition Function Write a program that accepts two positive binary number in string and perform the addition with Lab05.2 function enhance in a way can accept binary string in addition to decimal string (use input parameter to control the base2 or base10 addition) and output the as binary string. (Optional: Demonstrate 8 bits and 16 bits in length as inputs.) // the example function prototype for addition function below where accepting two numbers, m, and base as input; output the addition result as string type as return value; base should be 2 or 10 as required. string addFunction(string numberA, string numberB, int m, int base); Requirement: C++ programing; program an addition algorithm function that can both accept binary and decimal addition; convert each other if necessary. ................................................................................................................................................................................................................
Requirement:
1. Write a string addFunction that both can accept two positive binary numbers and decimal numbers in string.
2. The example function prototype for addition function below where accepting two numbers,m, and base as input; output the addition result as string type as return value; base should be 2 or 10 as required.
3. Output needs as binary string.
4. Example for String addFuntion(string numberA, string number B, int m, int base).
Program language: C++
c++ code:
#include<iostream>
#include<sstream>
#include<string>
#include<cmath>
using namespace std;
string convertIntegerToString(int num)
{//to convert integer to binary.
ostringstream str1;
str1<<num;
return str1.str();
}
string binaryAddition(int res)
{
//for binary number addition
string result="";
while(res>0)
{
int num=(res%2);
result+=convertIntegerToString(num);
res/=2;
}
for(int i=0,j=result.size()-1;i<j;i++,j--)
{ //to reverse the converted string.
char ch=result[i];
result[i]=result[j];
result[j]=ch;
}
return result;
}
string addFunction(string m,string n, int base)
{
int num1=0,num2=0;
if(base==2)
{ //convert the binary to decimal number
int j=0;
for(int i=m.length()-1;i>=0;i--)
{
if(m[i]-'0'==1)
{
num1+=pow(2.0,j);
}
j++;
}
j=0;
for(int i=n.length()-1;i>=0;i--)
{
if(n[i]-'0'== 1 )
{
num2+=pow(2.0,j);
}
j++;
}
}
else
{ //convert the positive number string to
integer
int j=0;
for(int i=0;i<m.length();i++)
{
num1=num1*10+m[i]-'0';
}
j=0;
for(int i=0;i<n.length();i++)
{
num2=num2*10+n[i]-'0';
}
}
return binaryAddition(num1+num2); //return the
binary addition of two number.
}
int main()
{
string m,n;
int base;
cin>>m>>n>>base; //input the two integer
and base.
cout<<"Addition of two number:
"<<addFunction(m,n,base)<<endl; //call to the
function.
}
output:
Decimal number addition:
Binary number addition: