I'm new to python and trying to wrap my head around bit manipulation, specifically using a relay board. In the code I'm working with I see:
class relay_data(dict):
address = {
"1":"2",
"2":"8",
"3":"20",
"4":"80",
"5":"1",
"6":"4",
"7":"10",
"8":"40",
"all":"FF"
}
def testBit(int_type, offset):
mask = 1 << offset
return(int_type & mask)
def get_relay_state( data, relay ):
if relay == "1":
return testBit(data, 1)
if relay == "2":
return testBit(data, 3)
if relay == "3":
return testBit(data, 5)
if relay == "4":
return testBit(data, 7)
if relay == "5":
return testBit(data, 2)
if relay == "6":
return testBit(data, 4)
if relay == "7":
return testBit(data, 6)
if relay == "8":
return testBit(data, 8)
Can someone explain how get_relay_state() works?
1 Answer 1
This is simple bit-arithmetic: get_relay_state() does shift a 1 left by relay positions and then mask the data with it.
So in common speech: it checks if the relay's bit is set. But the mapping is not linear.
For example:
if relay == "1":
return testBit(data, 1)
if relay == "3":
return testBit(data, 5)
The first if checks if relay is 1 is set and returns 2 (2nd bit) if so.
The second if checks if relay is 3 is set and returns 20 (5th bit) if so.
The values of the array relay_data coincide with the return value of the function get_relay_state().
The final expression return(int_type & mask) returns TRUE if the bit is set and FALSE if not.
Comments
Explore related questions
See similar questions with these tags.
testBit, the rest of the code is specific to some other purpose you haven't described at all, so I'm not sure we can help you with it. Therelay_dataclass isn't used at all in the functions, so it doesn't do anything at all as far as I can tell.