[Tutor] How to convert an integer into a binary?

lumbricus@gmx.net lumbricus@gmx.net
Wed, 8 Aug 2001 10:26:13 +0200


On Wed, Aug 08, 2001 at 03:36:04PM +0900, Haiyang wrote:
> How can I convert an interger into a binary code in Python?

Hello!

This should become a faq ;-)

import sys
e=[]
try:  
	z=int(raw_input("Number?\n> "))
except:
	print "Need a number."
	sys.exit(1)
while (z > 0):
	if (z & 1) == 1:
		e.append(1)
	else:   
 		e.append(0)
        z=z>>1
e.reverse()
print e
	 

> 
> Thank you.

HTH and Greetings J"o!
:-)

-- 
Life would be so much easier if we could just look at the source code.
	-- Dave Olson