Can string formatting be used to convert an integer to its binary form ?

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Thu Sep 28 17:38:09 EDT 2006


In <efhdt1$9a1$1 at mlucom4.urz.uni-halle.de>, Mirco Wahab wrote:

> Thus spoke Frederic Rentsch (on 2006-09-28 20:43):
>> bearophileHUGS at lycos.com wrote:
>>> Mirco Wahab:
>>>   
>>>> But where is the %b in Python?
>>>
>>> Python doesn't have that. ...
>>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528
>>   
>> Good idea, but shorter with -> 
>> http://cheeseshop.python.org/pypi/SE/2.2%20beta
>> SE.SE ('se_definition_files/int_to_binary.se') ('%X' % 987654321)
>> '00111010110111100110100010110001'
> 
> I don't really understand here:
> 
> - why doesn't have Python such a simple and useful thing as to_binstr(...)

Maybe simple, but useful?  And if you really need this it's simple to
implement or look up in the cook book.

> - why would you favor such complicated solutions
>   for this (as posted), when you can have this
>   in one line, e.g.:
> 
>   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.  ;-)

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list