Integer to "binary string"?
Dan Bishop
danb_83 at yahoo.com
Mon Dec 16 22:43:13 EST 2002
Alfred Morgan <amorgan at netlojix.com> wrote in message news:<3DFE6179.4030601 at netlojix.com>...
> I decided to write a version 2 of my bin function. Since version 1
> couldn't handle negative numbers I added an assertion otherwise it would
> get stuck in an infinite loop. I also changed the way s added a '0' or
> '1' since Dan didn't like my "short-circuiting" and/or method.
> I like it this way much better anyway because it's more petite.
Your code wasn't *that* bad; I just didn't feel like explaining it ;-)
I still wish Python had a real ?: operator, though.
> def bin(i):
> assert i >= 0, "Can't be used for negative numbers."
> s = ''
> while i:
> s = '01'[i & 1] + s
> i >>= 1
> return s or '0'
Or you could make it a special case of a generalized base conversion function:
# Can anyone write this in fewer lines?
def intToStr(num, radix=10):
if num < 0: return '-' + intToStr(-num, radix)
if num < radix: return "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[num]
return intToStr(num // radix) + intToStr(num % radix)
def bin(num):
return intToStr(num, 2)
More information about the Python-list
mailing list