Base conversion method or module

Andrew Bennetts andrew-pythonlist at puzzling.org
Wed Dec 10 00:44:37 CET 2003


On Tue, Dec 09, 2003 at 11:20:43PM +0000, Jeff Wagner wrote:
> On Tue, 9 Dec 2003 17:45:20 +1100, Andrew Bennetts <andrew-pythonlist at puzzling.org> wrotf:
> >
> >In Python, integer literals beginning with '0' are in octal, just as how
> >literals beginning with '0x' are in hex, so 01011010 really is 266760:
> >
> >>>> print 01011010
> >266760
> >
> >So it looks like gmpy is functioning correctly.
> >
> >-Andrew.
> >
> 
> Ok, so I get rid of the leading 0 and here is what I get:
> 
> >>> gmpy.digits(1011010,10)
> '1011010'
> 
> why? How do I tell gmpy that 1011010 is binary and I want it to convert to decimal or hex?

You seem to be confusing the value of a number with its representation.

Python's 'int' type simply holds a value.  It doesn't know the difference
between 90, 0x5A, and int('1011010', 2).  They are all the same number, even
though they represented differently in source code.

So, what you *really* are trying to ask is:  "How do I take a representation
of a number in binary (i.e. base 2), and convert it to a representation in
decimal or hex?"

The answer is to first convert your representation to a value -- python's
builtin int can convert string representation of numbers with any base from
2 to 36, e.g.:

>>> int('1011010', 2)
90
>>> int('5A', 16)
90

(I wouldn't be surprised if gmpy also could do this, but I don't know gmpy)

Note that I am passing strings to int, not bare literals!  If I wrote
"int(1011010, 2)", python would compile 1011010 as a number in base 10, and
pass that number to int instead of the string representation of the number
we really want.

Then you want to pass this value to gmpy.digits, e.g.

    num = int('1011010', 2)
    print gmpy.digits(num, 16)

-Andrew.






More information about the Python-list mailing list