C++ easy way to convert int to string with unknown base

Viewed 3466

Here is code in Java:

int a = 456;
int b = 5;
String s = Integer.toString(a, b);
System.out.println(s);

Now I want the same in C++, but all the conversions i find convert to base 10 only. I ofc dont want to implement this by mysleft, why to write something what already exists

4 Answers

There is no standard function itoa, which performs conversion to an arbitrary calculus system. But for example, in my version of the compiler there is no implementation. My solution:

#include <string>

// maximum radix - base36
std::string int2string(unsigned int value, unsigned int radix) {
    const char base36[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::string result;
    while (value > 0) {
        unsigned int remainder = value % radix;
        value /= radix;
        result.insert(result.begin(), base36[remainder]);
    }
    return result;
}
Related