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) ?
Asked
Active
Viewed 3,023 times
2
-
1Conversion at compile-time, or at run-time? – Oliver Charlesworth Jan 15 '12 at 13:53
-
Do you mean conversion of a user-defined literal in an arbitrary base to base10? – pmr Jan 15 '12 at 13:59
1 Answers
5
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.

Kerrek SB
- 464,522
- 92
- 875
- 1,084
-
-
2@pmr: what else? A "number base" is nothing *but* a property of a lexical representation of a number. – Kerrek SB Jan 15 '12 at 14:04
-
1But he talks about templates. So he might want to do something like `from_base<6, intliteral_in_base_6>::value`. – pmr Jan 15 '12 at 14:19
-
In fact I wanted to do some operations on the converted number, like rotating the digits, and testing whether a certain digit is zero,..etc. For Decimal<-->Binary, bitset is ideal, so I hoped I could find another tempelate for arbitrary base. Perhaps I will use the code of Kerrek and define my own operations. – Tarek Jan 15 '12 at 14:29
-
@Tarek: Rotating digits definitely sounds like a string operation, so you should be able to work on the strings. If you really wanted to, you could of course implement something like a digit rotation on the numerical value directly, but you'd be going through the same steps essentially (just without storing the intermediate representation). – Kerrek SB Jan 15 '12 at 14:58
-
2For example, the value represented by the `k`th digit (0-based) is `((n / base^k) % base) * base^k`, so you could "set to zero" a certain digit and move it somewhere else etc. – Kerrek SB Jan 15 '12 at 15:00