integer to binary...

Grant Edwards grante at visi.com
Thu Jun 1 16:11:23 EDT 2006


On 2006-06-01, Tim Chase <python.list at tim.thechases.com> wrote:
>>>> for example I want to convert number 7 to 0111 so I can make some
>>>> bitwise operations...
>>> Just do it:
>>>
>>>>>> 7 & 3
>>> 3
>>>>>> 7 | 8
>>> 15
>> I know I can do that but I need to operate in every bit separeted.
>
>
> I suppose there might be other operations for which having them 
> as strings could be handy.  E.g. counting bits:
>
> bitCount = len([c for c in "01001010101" if c=="1"])
>
> or parity checking with those counted bits...sure, it can be done 
> with the raw stuff, but the operations often tend to be more obscure.

I would think an array or list of bits would be a lot more
useful for doing "bitwise operations":

bitCount = sum([0,1,0,0,1,0,1,0,1,0,1])
parity = reduce(operator.xor,[0,1,0,0,1,0,1,0,1,0,1])

> Other reasons for wanting an arbitrary integer in binary might be 
> for plain-old-display, especially if it represents bitmap data.

Yes. I thought C should have had a %b format since the
beginning, but nobody listens. But that's not
what the OP said he wanted it for.  

-- 
Grant Edwards                   grante             Yow!  Now I'm concentrating
                                  at               on a specific tank battle
                               visi.com            toward the end of World
                                                   War II!



More information about the Python-list mailing list