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
Here is a recursive version that handles signed integers and custom digits.
output:
to convert to any base, inverse is easy too.
A recursive solution for those interested. Of course, this will not work with negative binary values. You would need to implement Two's Complement.
I have not seen any converters of float here. And I missed the grouping for always three digits.
TODO:
-numbers in scientific expression
(n.nnnnnn*10**(exp)
-- the'10'
isself.baseDigits[1::-1]/self.to_string(len (self.baseDigits))
-from_string-function.
-base 1 -> roman numbers?
-repr of complex with agles
So here is my solution:
I made a pip package for this.
I recommend you use my bases.py https://github.com/kamijoutouma/bases.py which was inspired by bases.js
refer to https://github.com/kamijoutouma/bases.py#known-basesalphabets for what bases are usable
EDIT: pip link https://pypi.python.org/pypi/bases.py/0.2.2