1

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?

zx485
29.1k28 gold badges55 silver badges65 bronze badges
asked Mar 24, 2018 at 22:54
2
  • The only bit manipulation is happening in 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. The relay_data class isn't used at all in the functions, so it doesn't do anything at all as far as I can tell. Commented Mar 24, 2018 at 23:01
  • As a side note: You almost certainly don't want a class that inherits from dict if you don't want it to act like a dict and use the dict's internal storage in any way. (In fact, I don't think you want a class here at all.) Commented Mar 24, 2018 at 23:27

1 Answer 1

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.

answered Mar 24, 2018 at 23:08
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.