python - Pythonic way of checking bit values -


i have set of constants declarations

    self.poutput = 1     self.ppwm = 2     self.pinput = 4     self.punused = 8     self.psonar = 16     self.pultra = 32     self.pservod = 64     self.pstepper = 128     self.pcount = 256     self.pinputdown = 512     self.pinputnone = 1024 

what pythonic way of checking whether value matches of input states (4,512 , 1024) please? info: i'd use bit pattern checking in simpler languages wondered if there better way in python :) each pin can have 1 of i/o states above if pin of of input values 1 action occurs e.g if pin == 4 or 512 or 1024 -> something

testing set membership (which seem doing) best done using set.

self.input_states = {self.pinput, self.pinputdown, self.pinputnone}  # later if value in self.input_states:     do_something() 

of course handle in variety of essentially-identical ways, 1 way or have encode knowledge of these magic numbers "input states".


now if, has been suggested, want bit-masking or tests based on whether particular bit set, want take @ python bitwise operators. in particular, see if value equal 1 of ones you've got there, you'd use bitwise and, denoted & in python. joran's answer covers use well, basic idea is:

if value & self.pinput: # value has 1 in pinput bit (bit 3)     do_something() 

or if of input values trigger same action:

if any(value & p p in (self.pinput, self.pinputdown, self.pinputnone)):     do_something() 

Comments

Popular posts from this blog

php - Magento - Deleted Base url key -

javascript - Tooltipster plugin not firing jquery function when button or any click even occur -

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -