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++
SOLUTION-
I have given the c++ code below with commands for easy understanding and given screenshot also :)
CODE-
// main program
#include<iostream>
using namespace std;
string addFunction(string numberA, string numberB, int m, int
base) //function to get the binary number in string
{
string sol=""; //print the result
int carry=0;
int indexA=numberA.length()-1; //Store last index of
numberA in indexA
int indexB=numberB.length()-1; //Store last index of
numberB in indexB
while(indexA>=0 || indexB>=0) //Loop untill both
the strings finished
{
int a = (indexA>=0) ?
numberA[indexA]-'0' : 0; //If theres is a bit in numberA then take
it, 0 other
int b = (indexB>=0) ?
numberB[indexB]-'0' : 0; //If theres is a bit in numberB then take
it, 0 other
int sum = (a^b^carry);
//Find carry
carry = ((a & b) | (a
& carry) | (b & carry));
//Store the sum into result
string
sol=char(sum+48)+sol;
//Decrement both the
indiecs
indexA--;
indexB--;
}
//If there is a carry then add append 1 to the
front
sol=(carry==1)?"1"+sol:sol;
return sol;
}
int main()
{
//Function calling
cout<<"Addition:"<<addFunction("1001","100001101",4,2)<<endl;
cout<<"Addition:"<<addFunction("1111","11111",5,2)<<endl;
cout<<"Addition:"<<addFunction("1000","0100",4,2)<<endl;
return 0;
}
SCREENSHOT-
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I
WILL SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------