Welcome, guest | Sign In | My Account | Store | Cart

This function takes in any base-10 integer and returns the string representation of that number in its specified base-n form. The code was inspired from http://code.activestate.com/recipes/65212-convert-from-decimal-to-any-base-number/ , thereby improving upon it.

Python, 15 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def base10toN(num, base):
    """Change ``num'' to given base
    Upto base 36 is supported."""

    converted_string, modstring = "", ""
    currentnum = num
    if not 1 < base < 37:
        raise ValueError("base must be between 2 and 36")
    if not num:
        return '0'
    while currentnum:
        mod = currentnum % base
        currentnum = currentnum // base
        converted_string = chr(48 + mod + 7*(mod > 10)) + converted_string
    return converted_string

3 comments

Stephen Chappell 13 years, 1 month ago  # | flag

This code coverts both ways and allows for customization of the symbols used for different values: http://stackoverflow.com/questions/3973685/python-homework-converting-any-base-to-any-base/3973906#3973906

Marko Kukovec 10 years, 7 months ago  # | flag

Here is another solution:

'''
Created on 20. sep. 2013

@author: Kukovec
'''

def __DecimalToAnyBaseArrayRecur__(array, decimal, base):
    array.append(decimal % base)
    div = decimal / base
    if(div == 0):
        return;
    __DecimalToAnyBaseArrayRecur__(array, div, base)

def DecimalToAnyBaseArray(decimal, base):
    array = []
    __DecimalToAnyBaseArrayRecur__(array, decimal, base)
    return array[::-1]

def Test():
    print DecimalToAnyBaseArray(1258, 16)
    print DecimalToAnyBaseArray(1258, 10)
    print DecimalToAnyBaseArray(1258, 8)
    print DecimalToAnyBaseArray(1258, 2)

if __name__ == "__main__":
    Test()

Output:

[4, 14, 10]
[1, 2, 5, 8]
[2, 3, 5, 2]
[1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0]
Dave Iler 8 years, 11 months ago  # | flag

I really liked your conversion function, but there's a slight problem. When converting a number to base 16, when the digit just modded is a zero(base 16), a ':' is being printed instead of a '0'. This can be easily fixed. Here's where the problem is:

converted_string = chr(48 + mod + 7*(mod > 10)) + converted_string

In your test '(mod > 10)', it needs to be changed to either '(mod > 9)' or '(mod >= 10)'

Created by Shashwat Anand on Thu, 24 Feb 2011 (MIT)
Python recipes (4591)
Shashwat Anand's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks