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

Mirco Wahab peace.is.our.profession at gmx.de
Thu Sep 28 06:33:11 EDT 2006


Thus spoke Gabriel Genellina (on 2006-09-28 11:05):

> At Thursday 28/9/2006 05:22, Mirco Wahab wrote:
>> > But, can string formatting be used to convert an integer to its binary
>> > form ?
>>
>>   a = 199
>>   a_bin_str = pack('L', a)

> 
> Notice that the OP was looking for another thing, given the examples. 
> Perhaps a better wording would have been "how to convert an integer 
> to its base-2 string representation".

Yes, you are right. The OP looks for a
'binary (bit) representation ..."
I admit I didn't find out how to format
a value into a bit string in Python.

In Perl, this would be a no-brainer:

  $var = 199;
  $str = sprintf "%0*b", 32, $var;

and str would contain 00000000000000000000000011000111
on a intel machine.

But where is the %b in Python?

Regards & Thanks

Mirco



More information about the Python-list mailing list