Binary numbers

mensanator at aol.com mensanator at aol.com
Tue Jun 7 20:58:43 EDT 2005



Douglas Soares de Andrade wrote:
> Hi !
>
> How to work with binary numbers in python ? Is there a way to print a number
> in its binary form like we do with oct() or hex() ?
>
> Im doing a project that i have to work with binaries and i tired of convert
> numbers to string all the time to perform some operations.
>
> I searched about it in many places like python.org and google, but not found
> anything useful.
>
> Thats why im asking this.
>
> And another question... if python has not a way to do this, why i let me use
> oct(), hex() and not bin() ?
>
> Thanks for the help !
>
> --
> Douglas Soares de Andrade
> http://douglasandrade.cjb.net - dsa at unilestemg.br
> UnilesteMG - www.unilestemg.br
> ICQ, MSN = 76277921, douglas at tuxfamily.org

You might want to try the GMPY module:

>>> from gmpy import *
>>> help(digits)
Help on built-in function digits:

digits(...)
    digits(x[,base]): returns Python string representing x in the
    given base (2 to 36, default 10 if omitted or 0); leading '-'
    present if x<0, but no leading '+' if x>=0. x must be an mpz,
    or else gets coerced into one.

>>> x = 2**32 - 1
>>> print x
4294967295
>>> print digits(x,2)
11111111111111111111111111111111




More information about the Python-list mailing list