Converting an integer base 10 to a binary number

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

On Wed, 28 Mar 2001 15:35:20 +0200, Peter Stöhr <peter.stoehr at> 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)

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

Daniel Klein
Portland OR USA

More information about the Python-list mailing list