c++ template for conversion between decimal and arbitrary base

3.1k views Asked by At

Is there a c++ structure or template (in any library) that allows me to do conversion between decimal and any other base (much like what bitset can do) ?

1

There are 1 answers

6
Kerrek SB On

Yes, you can use unsigned int:

unsigned int n =   16; // decimal input
unsigned int m = 0xFF; // hexadecimal input

std::cout << std::dec << "Decimal: " << n << ", " << m << std::endl;
std::cout << std::hex << "Hexadecimal: 0x" << n << ", 0x" << m << std::endl;

Octal is also supported, though for other bases you had best write your own algorithm - it's essentially a three-liner in C++:

std::string to_base(unsigned int n, unsigned int base)
{
    static const char alphabet[] = "0123456789ABCDEFGHI";
    std::string result;
    while(n) { result += alphabet[n % base]; n /= base; }
    return std::string(result.rbegin(), result.rend());
}

The inverse unsigned int from_base(std::string, unsigned int base) function is similar.