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.
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
|
Tags: algorithms, base
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
Here is another solution:
Output:
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)'