user8968842
user8968842

Reputation:

Converting a base 10 number to any base without strings

I'm trying to make a function that takes in a number in base 10 and can be changed to any base from 2 though 9. I'm trying to only use the math module and just some simple math.

My code involves strings and I would like to eliminate them, and instead have the function do some math instead of using the numbers in a string. Also I'm trying to make the output integers.

def conver(n,b):
    digits = ('0123456789')
    ans = ""
    while n > 0:
        ans = digits[n%b] + ans
        n //= b
    return ans

For example the user could in put in the values (14,2) and get the output 1110

Upvotes: 2

Views: 6616

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

a simple implementation which can "convert" up to base 9 is as follows:

def conver(n,b):
    a = 0
    i = 0
    while n:
        n,r = divmod(n,b)
        a += 10**i * r
        i += 1

    return a

note that n,r = divmod(n,b) could be r = n % b; n //= b

Note that the number you're getting is an integer all right (as a type), but it makes no sense using it as such because the base is wrong: Ex: 1110 is not really 1110. So it's not really different than a string...

Well, that's just for the sake of the exercise.

Upvotes: 3

Related Questions