Converting an integer base 10 to a binary number

Daniel Klein danielk at aracnet.com
Thu Mar 29 17:06:31 CEST 2001


On Wed, 28 Mar 2001 15:35:20 +0200, Peter Stöhr <peter.stoehr at fh-hof.de> wrote:

>Hi out there,
>
>I know the int(x[,radix]) function that converts a string or a number
>(for a give radix) to an integer. Is there a built-in function that
>provides a conversion the other way round?
>Something like
>    bin(32) = "10000"

Methinks you will have to code this yourself. Hows about something like:

def toBinary(dec):
	bin = ''
	for x in range(8):
		bin = str(dec % 2) + bin
		dec = int(dec/2)
	return bin

>>> toBinary(32)
'00100000'

Of course this only works for 0 <= dec <= 255

Daniel Klein
Portland OR USA



More information about the Python-list mailing list