A. Alper Kunt
A. Alper Kunt

Reputation: 19

How to understand which bits are set to 1 in a bitarray

I am connected to a PLC with Python. This PLC, gives alarm conditions in an 8-bit representation. For example:

0110 0010

Each bit tells different conditions.

I want to create a list of conditions and print them together, like: door is on, alarms is off , lights are off, etc..

In the above example there are three different conditions. I want to show them together, all of them can be 1 or 0. How can I associate faults/conditions with bits?

Upvotes: 2

Views: 211

Answers (2)

LexyStardust
LexyStardust

Reputation: 1018

For these types of tasks I like to set up a dictionary with the bits mapped to the nice text representation. Because Python supports binary literals it's quite nicely self-documenting...

Something like:

status_lookup = { 0b00000001 : "Lights",
                  0b00000010 : "Fan",
                  0b00000100 : "Alarm",
                  0b00001000 : "Door"}

Then if you wanted a list of the currently "on" statuses:

bits = 0x0a # or whatever your input value was
currently_on = [status_lookup[i] for i in status_lookup if i & bits]

If you want to join them together in a string:

print("; ".join(currently_on))

As an alternative, if you're using Python 3.4+ you could do something similar using the new enum module:

from enum import IntEnum

class Status(IntEnum):
    Lights = 0b00000001
    Fan = 0b00000010
    Alarm = 0b00000100
    Door = 0b00001000

bits = 0x0a
currently_on = [x for x in Status if x & bits]

Upvotes: 3

wallyk
wallyk

Reputation: 57784

There are more elegant ways of doing it, but this will get you going:

s = ''
if value & 1:
    s += "lights on"
else:
    s += "lights off"

if value & 2:
    s += ", fan on"
else:
    s += ", fan off"

if value & 4:
    s += ", alarm on"
else:
    s += ", alarm off"

if value & 8:
    s += ", door on"  #?  "door open"?
else:
    s += ", door off"

Upvotes: 0

Related Questions