Converting an integer to base 2

Alves, Carlos Alberto - Coelce calves at coelce.com.br
Sat Dec 1 14:44:40 EST 2001


Yeah, it works. But not for n=0, when we get the wrong result '' intead '0'.
See below:
======================================================================
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> def ito2(n):
	if n < 1:
		return ''
	else:
		return itoa2(n / 2) + str(n & 1)

	
>>> ito2(0)
''
>>> 
========================================================================

I can modified the code do fix it, but it is appending the '0' string at the
begining of result. Maybe someone could resolvt it:
See the modified code below do the same, also to n=0, but adding '0' at head
of string.
def ito2(n):
	if n==0:
		return '0'
	elif n < 1 and n!=0:
		return ''
	else:
		return ito2(n / 2) + str(n & 1)

>>> ito2(4)
'0100'

> -----Original Message-----
> From: William Park [mailto:opengeometry at yahoo.ca]
> Sent: Friday, November 30, 2001 5:37 PM
> To: python-list at python.org
> Subject: Re: Converting an integer to base 2
> 
> 
> On Fri, Nov 30, 2001 at 10:16:16PM +0200, Erno Kuusela wrote:
> > def itoa2(n):
> >     if n < 1:
> >         return ''
> >     else:
> >         return itoa2(n / 2) + str(n & 1)
> 
> Brillant!
> 
> -- 
> William Park, Open Geometry Consulting, <opengeometry at yahoo.ca>.
> 8 CPU cluster, NAS, (Slackware) Linux, Python, LaTeX, Vim, Mutt, Tin
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20011201/15b154ff/attachment.html>


More information about the Python-list mailing list