Python allows easy creation of an integer from a string of a given base via
int(str, base).
I want to perform the inverse: creati
If you need compatibility with ancient versions of Python, you can either use gmpy (which does include a fast, completely general int-to-string conversion function, and can be built for such ancient versions -- you may need to try older releases since the recent ones have not been tested for venerable Python and GMP releases, only somewhat recent ones), or, for less speed but more convenience, use Python code -- e.g., most simply:
import string
digs = string.digits + string.ascii_letters
def int2base(x, base):
if x < 0:
sign = -1
elif x == 0:
return digs[0]
else:
sign = 1
x *= sign
digits = []
while x:
digits.append(digs[int(x % base)])
x = int(x / base)
if sign < 0:
digits.append('-')
digits.reverse()
return ''.join(digits)
Surprisingly, people were giving only solutions that convert to small bases (smaller then the length of the English alphabet). There was no attempt to give a solution which converts to any arbitrary base from 2 to infinity.
So here is a super simple solution:
def numberToBase(n, b):
if n == 0:
return [0]
digits = []
while n:
digits.append(int(n % b))
n //= b
return digits[::-1]
so if you need to convert some super huge number to the base 577
,
numberToBase(67854 ** 15 - 102, 577)
, will give you a correct solution:
[4, 473, 131, 96, 431, 285, 524, 486, 28, 23, 16, 82, 292, 538, 149, 25, 41, 483, 100, 517, 131, 28, 0, 435, 197, 264, 455]
,
Which you can later convert to any base you want
def base_changer(number,base):
buff=97+abs(base-10)
dic={};buff2='';buff3=10
for i in range(97,buff+1):
dic[buff3]=chr(i)
buff3+=1
while(number>=base):
mod=int(number%base)
number=int(number//base)
if (mod) in dic.keys():
buff2+=dic[mod]
continue
buff2+=str(mod)
if (number) in dic.keys():
buff2+=dic[number]
else:
buff2+=str(number)
return buff2[::-1]
I made my function to do this. Run well on windows 10, python 3.7.3.
def number_to_base(number, base, precision = 10):
if number == 0:
return [0]
positive = number >= 0
number = abs(number)
ints = [] # store the integer bases
floats = [] # store the floating bases
float_point = number % 1
number = int(number)
while number:
ints.append(int(number%base))
number //= base
ints.reverse()
while float_point and precision:
precision -= 1
float_point *= base
floats.append(int(float_point))
float_point = float_point - int(float_point)
return ints, floats, positive
def base_to_str(bases, string="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
"""bases is a two dimension list, where bases[0] contains a list of the integers,
and bases[1] contains a list of the floating numbers, bases[2] is a boolean, that's
true when it's a positive number
"""
ints = []
floats = []
for i in bases[0]:
ints.append(string[i])
for i in bases[1]:
floats.append(string[i])
if len(bases[1]) > 0:
return (["-", ""][bases[2]] + "".join(ints)) + "." + ("".join(floats))
else:
return (["-", ""][bases[2]] + "".join(ints))
Example:
>>> base_to_str(number_to_base(-6.252, 2))
'-110.0100000010'
Here is an example of how to convert a number of any base to another base.
from collections import namedtuple
Test = namedtuple("Test", ["n", "from_base", "to_base", "expected"])
def convert(n: int, from_base: int, to_base: int) -> int:
digits = []
while n:
(n, r) = divmod(n, to_base)
digits.append(r)
return sum(from_base ** i * v for i, v in enumerate(digits))
if __name__ == "__main__":
tests = [
Test(32, 16, 10, 50),
Test(32, 20, 10, 62),
Test(1010, 2, 10, 10),
Test(8, 10, 8, 10),
Test(150, 100, 1000, 150),
Test(1500, 100, 10, 1050000),
]
for test in tests:
result = convert(*test[:-1])
assert result == test.expected, f"{test=}, {result=}"
print("PASSED!!!")
>>> numpy.base_repr(10, base=3)
101
Note that numpy.base_repr()
has a limit of 36 as its base. Otherwise it throws a ValueError