Python allows easy creation of an integer from a string of a given base via
int(str, base).
I want to perform the inverse: creation of a string from an integer,
i.e. I want some function int2base(num, base)
, such that:
int(int2base(x, b), b) == x
The function name/argument order is unimportant.
For any number x
and base b
that int()
will accept.
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:
Those functions are not available on older versions of Python, with which I need compatibility with (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
Recursive
I would simplify the most voted answer to:
With the same advice for
RuntimeError: maximum recursion depth exceeded in cmp
on very large integers and negative numbers. (You could usesys.setrecursionlimit(new_limit)
)Iterative
To avoid recursion problems:
Python doesn't have a built-in function for printing an integer in an arbitrary base. You'll have to write your own if you want to.
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:
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
Great answers! I guess the answer to my question was "no" I was not missing some obvious solution. Here is the function I will use that condenses the good ideas expressed in the answers.