问题:
Python allows easy creation of an integer from a string of a given base via Python 允许通过给定基数的字符串轻松创建整数
int(str, base).
I want to perform the inverse: creation of a string from an integer , ie I want some function int2base(num, base)
, such that:我想执行相反的操作:从整数创建一个字符串,即我想要一些函数int2base(num, base)
,这样:
int(int2base(x, b), b) == x
The function name/argument order is unimportant.函数名称/参数顺序并不重要。
For any number x
and base b
that int()
will accept.对于int()
将接受的任何数字x
和基数b
。
This is an easy function to write: in fact it's easier than describing it in this question.这是一个易于编写的函数:实际上它比在这个问题中描述它更容易。 However, I feel like I must be missing something.但是,我觉得我一定错过了一些东西。
I know about the functions bin
, oct
, hex
, but I cannot use them for a few reasons:我知道函数bin
、 oct
、 hex
,但由于以下几个原因我不能使用它们:
Those functions are not available on older versions of Python, with which I need compatibility with (2.2)这些函数在旧版本的 Python 上不可用,我需要与 (2.2) 兼容
I want a general solution that can be called the same way for different bases我想要一个通用的解决方案,可以为不同的基础以相同的方式调用
I want to allow bases other than 2, 8, 16我想允许 2、8、16 以外的基数
Related有关的
- Python elegant inverse function of int(string, base) Python 优雅的 int(string, base) 反函数
- Integer to base-x system using recursion in python 在python中使用递归将整数转换为base-x系统
- Base 62 conversion in Python Python 中的 Base 62 转换
- How to convert an integer to the shortest url-safe string in Python? 如何将整数转换为 Python 中最短的 url 安全字符串?
解决方案:
参考一: https://stackoom.com/question/9VqM参考二: How to convert an integer to a string in any base?