user3566967 user3566967 - 15 days ago 6
C++ Question

Decimal to Hex converter using Recursion (C++)

Trying to write a program that converts a Decimal number to a Hexadecimal number that implements recursion.

Can't use stuff like

cout << hex << x << endl;


Need to know how to write the function manually.

I tried this but it didn't really work:

The input is an integer input by the user, and ss doesn't contain anything before this function.

string convertHex(int num, ostringstream &ss)
{

int x = num % 16;

switch (x)
{
case 10: ss << "A"; return ss.str(); break;
case 11: ss << "B"; return ss.str(); break;
case 12: ss << "C"; return ss.str(); break;
case 13: ss << "D"; return ss.str(); break;
case 14: ss << "E"; return ss.str(); break;
case 15: ss << "F"; return ss.str(); break;
default: ss << x; return ss.str(); break;
}

return convertHex(num / 16, ss);

}


Not sure if I fully understand how to convert from Decimal to Hex, but what's hanging me up more is getting it to work with recursion. Any ideas?

EDIT:

I added in the if statement that was suggested by awesomeyi, and took out the returns in the switch, and now it sort of works... but not really. Here's the new code:

string convertHex(int num, ostringstream &ss)
{

int x = num % 16;

if (num == 0)
{
ss << 0;
return ss.str();
}

switch (x)
{
case 10: ss << "A"; break;
case 11: ss << "B"; break;
case 12: ss << "C"; break;
case 13: ss << "D"; break;
case 14: ss << "E"; break;
case 15: ss << "F"; break;
default: ss << x; break;
}

return convertHex(num / 16, ss);

}


It works, but the output is backwards, and it adds a zero to the end of it. If I convert 16 in decimal to hex, it gives me 010. If I give it a bigger number like 4598, it gives me 6F110. The correct hex value for 4598 is 11F6.

This is for a school assignment. Should I actually try to amend this? Or should I just flip it around after the function?

Answer

It print backwards because that's what you define in your recursion :)

Basically it should look like this:

(psuedo code)

printHex(int i) {
    if i == 0 {
        // do nothing
        return;
    }

    printHex( i / 16);
    print out hex value of i %16
}

if you are going to return a string, similarly, it should look like:

(psuedo code)

string toHex(int i) {
    if (i == 0)  {
        return "";
    }

    return toHex(i/16) + convertToHex( i % 16);
}