Python允许从给定基数的字符串中轻松创建一个整数
int(str, base).
我想执行相反的操作:从一个整数创建一个字符串,
例如,我想要一些函数int2base(num, base),这样:
int(int2base(x, b), b) == x
函数名/参数的顺序并不重要。
对于int()将接受的任何以b为底的数字x。
这是一个很容易写的函数:事实上,它比在这个问题中描述它更容易。然而,我觉得我一定是错过了什么。
我知道函数bin, oct, hex,但我不能使用它们的几个原因:
这些函数在旧版本的Python中不可用,我需要与(2.2)兼容
我想要一个通解对于不同的碱都可以用同样的方式表示
我想允许2 8 16以外的底数
相关的
Python优雅的int(string, base)逆函数
在python中使用递归的整数到base-x系统
Python中的Base 62转换
如何在Python中将整数转换为最短的url安全字符串?
很棒的答案!
我想我问题的答案是“不”,我并没有错过一些明显的解决方案。
下面是我将使用的函数,它可以浓缩答案中所表达的好想法。
允许调用者提供的字符映射(允许base64编码)
检查负数和零
将复数映射为字符串元组
def int2base(x,b,alphabet='0123456789abcdefghijklmnopqrstuvwxyz'):
'convert an integer to its string representation in a given base'
if b<2 or b>len(alphabet):
if b==64: # assume base64 rather than raise error
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
else:
raise AssertionError("int2base base out of range")
if isinstance(x,complex): # return a tuple
return ( int2base(x.real,b,alphabet) , int2base(x.imag,b,alphabet) )
if x<=0:
if x==0:
return alphabet[0]
else:
return '-' + int2base(-x,b,alphabet)
# else x is non-negative real
rets=''
while x>0:
x,idx = divmod(x,b)
rets = alphabet[idx] + rets
return rets
令人惊讶的是,人们给出的答案只能转换成小基数(比英语字母表的长度还小)。没有人试图给出一个可以转换为2到无穷任意底数的解。
这里有一个超级简单的解决方案:
def numberToBase(n, b):
if n == 0:
return [0]
digits = []
while n:
digits.append(int(n % b))
n //= b
return digits[::-1]
所以如果你需要把一个超级大的数转换成577的底数,
numberToBase(67854 ** 15 - 102,577),将为您提供正确的解决方案:
[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],
你以后可以把它转换成任何你想要的基数
at some point of time you will notice that sometimes there is no built-in library function to do things that you want, so you need to write your own. If you disagree, post you own solution with a built-in function which can convert a base 10 number to base 577.
this is due to lack of understanding what a number in some base means.
I encourage you to think for a little bit why base in your method works only for n <= 36. Once you are done, it will be obvious why my function returns a list and has the signature it has.