Can string formatting be used to convert an integer to its binary form ?
Mirco Wahab
wahab at chemie.uni-halle.de
Thu Sep 28 18:20:39 EDT 2006
Thus spoke Marc 'BlackJack' Rintsch (on 2006-09-28 23:38):
>> def int2bin(num, width=32):
>> return ''.join(['%c'%(ord('0')+bool((1<<k)&num)) for k in range((width-1),-1,-1)])
>
> Yeah, I wonder why not everybody sees the beauty in this cool and
> straightforward one liner. ;-)
Right. I see this is BS, maybe lots of these lines exist already,
one could come up with (sorted by obfuscation, descending):
def int2bin(num, width=32):
# return ''.join( [chr(ord('0')+bool(1<<k & num))for k in range(width-1,-1,-1)] )
# return ''.join( map(lambda k:str(num>>k & 1),range(width-1, -1, -1)) )
# return ''.join( [str(num>>k & 1)for k in range(width-1, -1, -1)] )
But after some thinking, I thought about discussing this one:
def i2b(num, width):
return str(1 & num>>(width-1)) + i2b(num, width-1) if width else ''
which is the shortest ;-)
(Sorry but I'm more or less a newbie, maybe this is BS too ...)
Regards
Mirco
More information about the Python-list
mailing list