Dumb python questions

Alex Martelli aleaxit at yahoo.com
Sat Aug 18 19:26:31 EDT 2001


"Paul Rubin" <phr-n2001 at nightsong.com> wrote in message
news:7xr8u96tni.fsf at ruckus.brouhaha.com...
    ...
> Here's one: say I have a long int, like x = 7**77777L.  How can I tell
> how many bits it takes to express that number in binary?  How can I

>>> x = 7**77777L
>>> import gmpy
>>> print gmpy.numdigits(x,2)
218348

so I think you need 218,348 bits (could be 218,347: gmpy just
wraps GMP, the GNU MP library, and GMP in turn sometimes gives
an extra digit when asked for number of digits of a number in
a certain base).  I know of no fast way to do this in 100% pure
Python, which was one of my motivations for wrapping GMP into
GMPY (*fast* moltiplication of long numbers being another).

> convert it into a packed character string (i.e. represent it in string
> form with 8 bits/char so I can write it to a file)?  The answers I can

>>> zz = gmpy.binary(x)
>>> type(zz)
<type 'string'>
>>> len(zz)
27294
>>> len(zz)*8
218352
>>> zz[:4]
'\x87\xb4&\xd7'
>>> zz[-4:]
'\xb1\xd0\x7f\x0c'
>>>

zz is a string of 27294 bytes (218352 bits, 4 more than x's
length due to rounding) that represents it as binary (little
endian base-256).

> think of involve weird kludges and/or are unacceptably slow.

GMP is pretty fast, and so is its wrapper GMPY.  See
gmpy.sf.net.  I don't think it's a "weird kludge" to wrap
a good multiprecision library to get at its functionality
from Python -- I think it's rather Pythonic, actually.


Alex






More information about the Python-list mailing list