Integer to "binary string"?
Anton Vredegoor
anton at vredegoor.doge.nl
Tue Dec 17 09:37:28 EST 2002
On 16 Dec 2002 19:43:13 -0800, danb_83 at yahoo.com (Dan Bishop) wrote:
>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)
It was special cased too soon :-)
def intToStr(num, radix=10):
if num < 0: return '-' + intToStr(-num, radix)
if num < radix: return "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[num]
return intToStr(num // radix,radix) + intToStr(num % radix,radix)
Works a lot better with bin as defined above!
Regards,
Anton.
More information about the Python-list
mailing list