Can string formatting be used to convert an integer to its binary form ?
Mirco Wahab
wahab at chemie.uni-halle.de
Thu Sep 28 17:08:26 EDT 2006
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(...)
even C++ has one built in,
#include <iostream>
#include <bitset>
int somefunc()
{
int val = 199;
std::cout << std::bitset<32>( val );
...
- 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)])
(including a string with specifier,this is what I came up with after
looking up some Python docs - maybe you can straighten this a bit ...)
-- but my goggles might be biased,
I don't really emphasize the "Python way" ;-)
Regards and thanks
Mirco
More information about the Python-list
mailing list