Add this before line 23:
cout << "dtoh(" << number << ',' << s <<")\n";
and this before line 50:
cout << '\n';
The output is now:
dtoh(1728,)
dtoh(108,0)
dtoh(6,0C)
dtoh(0,0C6)
6C
6C
C
|
So the problem is that each recursive call prints a part of the output.
This will sound harsh, but I think you should throw this out and start again. There is no need for recursion, or retrieveHexChar, or a stringstream. The function should return a string that main() outputs.
So the function should be
string numberToHex(int number)
You have the right idea for stripping off one hex digit at a time:
1 2
|
int temp = number % 16;
number = number/16;
| |
Next you need to get the hex character that corresponds to temp. Here's one way to do it:
1 2 3
|
char ch;
if (temp <10) ch = temp + '0';
else ch = temp-10 + 'A';
| |
This works when the numeric code for digits are consecutive from 0 to 9, and then the code for letters is consecutive from A to (at least) F. The people who developed ASCII were smart enough to do this.
Another way to do it is with a lookup table:
1 2
|
const char hexDigits = "0123456789ABCDEF";
char ch = hexDigits[temp];
| |
Once you have the digit, append it to the result string.
Now put the whole thing inside a loop instead of loop:
1 2 3 4
|
while (number) {
int temp = number % 16;
etc.
}
| |
This will produce a string that is in the reverse order of what you want. Use string::reverse() to reverse it.