2

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) ?

Sufian Latif
  • 13,086
  • 3
  • 33
  • 70
Tarek
  • 1,060
  • 4
  • 17
  • 38

1 Answers1

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
  • Is printing in different bases what OP really wants? – pmr Jan 15 '12 at 13:59
  • 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
  • 1
    But 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
  • 2
    For 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