How to test whether bit is set within a flag with Python ?

cjw cjw at ncf.ca
Wed May 12 14:55:09 EDT 2010


On 12-May-10 14:40 PM, MRAB wrote:
> robert somerville wrote:
>> I am trying to determine how to test whether variors bits are set
>> within a byte (or larger flag) , the python 'and' and 'or' do not seem
>> to be doing what i want .. does anybody have some sample code showing
>> how to do it ??
>>
>> e.g. (in "C")
>>
>> unsigned char a = 6;
>>
>> is 3rd bit set ??
>>
>> a & 4 =, true in this case ....
>>
> 'and', 'or' and 'not' are Boolean.
>
> Python borrows its bitwise operators from C:
>
> & bitwise and
> | bitwise or
> ^ bitwise xor
> ~ bitwise not (ones' complement)
> << shift left
>  >> shift right
>
> You also need to remember that Python's integers are of (virtually)
> unlimited length.

a= 6
if a & 2:
   print 'hit'
else:
   print 'miss'

This hits.

Colin W.




More information about the Python-list mailing list