如何将整数转换为任何基数的字符串? - How to convert an integer to a string in any base?

问题:

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:我知道函数binocthex ,但由于以下几个原因我不能使用它们:

  • 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有关的


解决方案:

参考一: https://stackoom.com/question/9VqM
参考二: How to convert an integer to a string in any base?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章