Search code examples
pythonbit-manipulationbitwise-operators

Need help unpacking bit values


I need some help / guidance on unpacking a value that represents bits in Python. I am parsing through json objects and there is a field that represents the number of flags that describe the problem using bit values.

For example, a value of 24 means that both bits 3 and 4 are set (8 + 16 = 24) so it has msg4 and msg5. I know I need to use bitwise operators, but I don't really understand how to unpack the value into separate bits.

From the documentation of the API I'm using:

bit 0 (1) - example msg1

bit 1 (2) - example msg2

bit 2 (4) - example msg3

bit 3 (8) - example msg4

bit 4 (16) - example msg5

bit 5 (32) - example msg6


Solution

  • If val is your value:

    if val & (1 << 0):
      # msg1
    elif val & (1 << 1):
      # msg2
    elif val & (1 << 2):
      # msg3
    and so on
    

    If you finding explicit powers of two clearer than the shifts, you could also write

    if val & 1:
      # msg1
    elif val & 2:
      # msg2
    elif val & 4:
      # msg3
    and so on