I have a number of nodes that can be grouped to respond to commands via a bitmask. For example: NodeA is in groups 1 and 5. When asked which groups it belongs to, it answers with 17 of which the binary equivalent is '0b10001'. A node in groups 2, 7 and 9 would tell me it belongs to group 322 ('0b101000010'). I need a way to display to the user which group a specified node belongs to. There are a possibility of 16 groups. My code will give me a 'string index out of range' error if the binary is not 16 characters long. I know there is a better way:
def xref(grp):
a = bin(grp)
d = str(a)
if d[-1] == '1':
print "Group 1"
if d[-2] == '1':
print "Group 2"
if d[-3] == '1':
print "Group 3"
repeat for 16 groups
You just need to use some basic bitwise operators.
Here's an example:
def findbits(num):
for i in range(16):
if num & 1 << i:
print("Group {0}".format(i + 1))
And the results:
>>> findbits(0b10001) Group 1 Group 5 >>> findbits(0b10100010) Group 2 Group 6 Group 8 >>> findbits(0b101000010) Group 2 Group 7 Group 9
What this does is loop through the 16 bits you want to look at.
1 << i shifts the number 1 by i bits, e.g. 1 << 4 would be 0b10000So what this does is compare your values against 0b1, 0b10, 0b100, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With