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
http://code.activestate.com/recipes/65212/
Here's another one from the same link
explanation
In any base every number is equal to
a1+a2*base**2+a3*base**3...
The "mission" is to find all a 's.For every
N=1,2,3...
the code is isolating theaN*base**N
by "mouduling" by b forb=base**(N+1)
which slice all a 's bigger than N, and slicing all the a 's that their serial is smaller than N by decreasing a everytime the func is called by the currentaN*base**N
.Base%(base-1)==1 therefor base**p%(base-1)==1 and therefor q*base^p%(base-1)==q with only one exception when q=base-1 which returns 0. To fix that in case it returns 0 the func is checking is it 0 from the beggining.
advantages
in this sample theres only one multiplications (instead of division) and some moudulueses which relatively takes small amounts of time.
output:
Another solution, works with base 2 to 10, needs modification for higher bases:
Example: