Question
Hey I need help fixing this error. It says out of range. Any help wiil be highly appreciated. C++ program to add hexadecimal numbers. Other
Hey I need help fixing this error. It says out of range. Any help wiil be highly appreciated.
C++ program to add hexadecimal numbers. Other functions cannot be added, and it SHOULD NOT t be changed into decimal, perform the addiditon and convert back to hexadecimal
#include
// NOTE: The ONLY files that should be #included for this assignment are iostream, vector, and string // No other files should be #included
using namespace std;
string addhex(string, string);
int main()
{
cout << "hexadecimal A4 + A5 = " << addhex("A4", "A5") << endl; //you should get 149
cout << "hexadecimal 2B + C = " << addhex("2B", "C") << endl; //you should get 37
cout << "hexadecimal FABC + 789 = " << addhex("FABC", "789") << endl; //you should get 10245
cout << "hexadecimal FFFFFF + FF = " << addhex("FFFFFF", "FF") << endl << endl; //you should get 10000FE
system("PAUSE");
return 0;
}
string addhex(string hex1, string hex2)
{
string result;
int sum = 0;
bool carry = false;
while (hex1.size() != hex2.size())
{
if (hex1.size() > hex2.size())
{
hex2.insert(0, "0");
}
else
{
hex1.insert(0, "0");
}
}
for (int i = hex1.size(); i >= 0; i--)
{
if (hex1.at(i) >= 0 && hex1.at(i) < 10)
{
sum += hex1.at(i) - '0';
}
else
{
sum += hex1.at(i) - 'A' + 10;
}
if (hex2.at(i) >= 0 && hex2.at(i) < 10)
{
sum += hex2.at(i) - '0';
}
else
{
sum += hex2.at(i) - 'A' + 10;
}
sum += (1 * carry);
carry = (sum >= 16);
sum = sum % 16;
if (sum <= 9)
{
result += '0' + sum;
}
else
{
result += 'A' + (sum - 10);
}
}
carry ? result += '1' : result = result;
return string(result.rbegin(), result.rend());
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started