如何將整數轉換爲任何基數的字符串? - 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?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章