Search code examples
c++stackradix

converting from decimal base to hexadecimal base c++


I want to convert from base larger than 10 (11 to 16). This code only converting to base 2-9. How do i convert let say 299 in base 10 = 12B in base 16, 14E in base 15, 1A0 in base 13.... Same goes. Where/how my codes should be? Thank you in advance.

using namespace std;

int main()
{
    stack <int> mystack;
    int input;
    int base;

    cout << "Please enter an integer to be converted (base 10): ";
    cin >> input;
    cout << "Base (2 to 16): ";
    cin >> base;

    do {
        int x = input % base;
        mystack.push(x);
    } while (input = input / base);

    cout << "\nThe base " << base << " is:\n";
    while (!mystack.empty())
    {
        int x = mystack.top();
        cout << x << " ";
        mystack.pop();
    }
    cout << "\n\n";
}

Solution

  • Your conversion code is correct: mystack contains the right digits, in reverse order.

    Your printing code is wrong, though: cout << x << " "; with x being an int will print digits, for bases 11 and above you need letters as well.

    One approach is to make a string of digits, and use x as an index into it:

    std::string digits("0123456789ABCDEF");
    ...
    while (!mystack.empty()) {
        int x = mystack.top();
        cout << digits[x] << " ";
        mystack.pop();
    }