converting to a binary number?

mensanator at aol.com mensanator at aol.com
Fri Mar 24 15:09:54 EST 2006


John Salerno wrote:
> I'm having some trouble finding a function that converts numbers
> (whether integer, hex, whatever) to its binary representation. Is there one?
>
> Thanks.

Get the Gnu Multiple Precision library for Python module (Google GMPY).

>>> import gmpy
>>> help(gmpy.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.

>>> for i in range(16):
	print gmpy.digits(i,2)
	
0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111




More information about the Python-list mailing list