integer to binary...

Tim Chase python.list at tim.thechases.com
Thu Jun 1 16:02:59 EDT 2006


>>> 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.

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

If you just want to operate on each bit, you can iterate over the 
number of bits and shift a single bit to its position:

 >>> target = 10
 >>> shift = 0
 >>> while 1 << shift <= target:
...     print "Bit %i is %i" % (shift,
...		(target & (1 << shift)) >> shift)
...     shift += 1
...
Bit 0 is 0
Bit 1 is 1
Bit 2 is 0
Bit 3 is 1


It's ugly, but it works...

-tkc






More information about the Python-list mailing list