Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python finding the 1's in a bitmask

Tags:

python

bitmask

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
like image 394
Cathy_Hanna Avatar asked Feb 11 '26 11:02

Cathy_Hanna


1 Answers

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 0b10000
  • num & whatever does a bitwise AND - each bit of the number is set to 1 if the bits of the two operands are 1.

So what this does is compare your values against 0b1, 0b10, 0b100, etc.

like image 123
Scott Mermelstein Avatar answered Feb 13 '26 23:02

Scott Mermelstein