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

Christopher Smith csmith@blakeschool.org
Wed, 08 Aug 2001 08:43:20 -0500


lumbricus@gmx.net wrote:
| 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?
| > "))
| 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
| 	 

Thanks for the bit-operations approach!  (Watch out for the trivial z=0
case, though, which should return e=[0] instead of [].)  It inspired me to 
change the approach that I had taken when needing this function.  Here's
what I came up with:

def d2b(numb,b=2):
	'''Returns a list containing the base b representation of 
	the decimal number, big end first.
	'''
	l=[numb]
	while l[0]>=b:
		l.insert(1,0)
		l[0],l[1]=divmod(l[0],b)
	return l

There's already a version on the Useless site.  Coupling
what you had (case for b==2) with the above might make for a good 
addition, though.

/c