Converting an integer to base 2

Erno Kuusela erno-news at erno.iki.fi
Fri Nov 30 15:16:16 EST 2001


In article <3C07CFED.C7F7CA38 at motorola.com>, Stephen Boulet
<stephen.boulet at motorola.com> writes:

| I'm trying to convert integers to base 2. Can someone tell me why this
| doesn't work?

def itoa2(n):
    if n < 1:
        return ''
    else:
        return itoa2(n / 2) + str(n & 1)

>>> for n in 123, 123411, 4569, 12341234, 2456:
...     s = itoa2(n)
...     print n, s, string.atoi(s, 2)
...
123 1111011 123
123411 11110001000010011 123411
4569 1000111011001 4569
12341234 101111000100111111110010 12341234
2456 100110011000 2456


(i saw this here some years ago, couldn't find the original post or
author)

  -- erno



More information about the Python-list mailing list