Search code examples
c++typesradix

Number Base conversion and digits access?


The language is c++

I have to read in some data from 0 - n, n could theoretically be infinity. Based on the value of n, I have to change the numbers over from decimal to that base, even if its base 10000. So if I read in 5 numbers, n=5, I have to convert them over to base5.

That said, I am not sure how to do the conversion, but I'm sure I could get it reading over some article. But what really concerns me is when I convert over to whatever the n base might be what type would my result be to store in an array? Long?

Once I get the converted numbers in some array, how would I access each individual digit in each number for manipulation later?

Thanks.


Solution

  • Conversion from decimal to base is done by division / modulo. x is the decimal number, b is the target base.

    1. r = x % b
    2. y = (x-r) : b
    3. replace x by y and repeat from 1 until y becomes 0
    4. the result are the r's, bottom up

    Beneath of that you'll have to create a std::map with replacement patterns for the numbers in r, i. e. for base 16 some entries would be 10 -> A, 11 -> B. This implies, that you'll have to think about a representation form for very large n.

    BTW: Consider a book about programming 101, conversion of decimal to bin / oct / hex is always explainend and easily adaptable for other bases.