Hi this is a c++ problem. The goal is to create two functions for binary number
ID: 3750765 • Letter: H
Question
Hi this is a c++ problem. The goal is to create two functions for binary number addition and hexadecimal number addition. The first function is supposed to take two binary numbers as a string and give the result by adding them as a string. The second function is supposed to take two hexadecimal numbers as a string and give the result by adding them as a string. I am almost done. The first function works fine but I’m having problem with the second function. The second function works for some numbers but not for all. I cannot figure out what’s wrong with this function. Thanks in Advance.// NOTE : The ONLY files that should be #included for this assignment are otrean, vector, and string :// No other files should be #included #include #include #include // NOTE: The ONLY file that should be #included for this assignment are ARnttsam, vector, and atring 9 No other files should be fincluded 2 2 using namespace std 4 string addbin (string, string): 5 tring addhex (string, string) 18 int main O 20 coutcc"binary 1101 1000 -
Explanation / Answer
Fixed this decimal code here it is
#include <iostream>
using namespace std;
string addhex(string hex1, string hex2);
int main()
{
cout << "Hexadecimal A4 + A5 = " << addhex("A4", "A5") << endl;
cout << "Hexadecimal 2B + C = " << addhex("2B", "C") << endl;
cout << "Hexadecimal FABC + 789 = " << addhex("FABC", "789") << endl;
cout << "Hexadecimal FFFFFF + FF = " << addhex("FFFFFF", "FF") << endl;
cout << "Hexadecimal 1 + ABCD = " << addhex("1", "ABCD") << endl;
return 0;
}
string addhex(string hex1, string hex2)
{
string result = "";
int s = 0;
char c1, c2;
int i = hex1.size()-1, j = hex2.size()-1;
while(i >= 0 || j >= 0 || s == 1) {
c1 = hex1[i];
c2 = hex2[j];
if(i >= 0 && c1 >= '0' && c1<= '9') {
s += c1 - 48;
}
else if( i >=0 && c1 >= 'A' && c1 <= 'F') {
s += c1-55;
}
else {
s += 0;
}
if(j >= 0 && c2 >= '0' && c2<= '9') {
s += c2 - 48;
}
else if( j >=0 && c2 >= 'A' && c2 <= 'F') {
s += c2-55;
}
else {
s += 0;
}
int digit = s % 16;
if (digit <= 9) {
result = char(s%16 + 48) + result;
}
else {
result = char(s%16 + 55) + result;
}
s = s/16;
i--; j--;
}
return result;
}
here is sample execution
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.