Hex addition C++

I'm writing a program to add two hexadecimal digits, and I've come across a problem. It seems to add the number to the first digit. If i put in AB and 1, it would tell me that the answer is BB, but that's wrong. It should be AC. Here's my code (this is just one function, and the problem is here apparently):



//converts answer in decimal to hex
void backToHex( int result[], int result2[], int size)
{
char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
int answer[10] = {0};

for (int i = 0; i < 10; i++)
{
answer[i] = answer[i] + result[i] + result2[i];
if (answer[i] > 15)
{
answer[i + 1] = answer[i] / 16;
answer[i] %= 16;
}
}
if (answer[9] > 15)
cout << "----------Addition Overflow----------" << endl;

else
for (int i = 0; i < 10; i++)
cout << hex[answer[i]];
cout << endl << answer[0] << answer[1] << endl;

}








Can you show what the input arrays are?

Are they something like this?

1
2
    int result = {10,11,0,0,0,0,0,0,0,0};
    int result2 = {0,1,0,0,0,0,0,0,0,0};



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//converts answer in decimal to hex
void backToHex( int result[], int result2[], int size)
{
char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
int answer[10] = {0};

for (int i = 0; i < 10; i++)
{
answer[i] = answer[i] + result[i] + result2[i];
if (answer[i] > 15)
{
answer[i + 1] = answer[i] / 16; /// When i is 9, i+1 is 10, highest index of answer allowed should be 9!!!
answer[i] %= 16;
}
}
if (answer[9] > 15)
cout << "----------Addition Overflow----------" << endl;

else
for (int i = 0; i < 10; i++)
cout << hex[answer[i]];
cout << endl << answer[0] << answer[1] << endl;

}
Last edited on
Topic archived. No new replies allowed.