Search code examples
pythonlistbit-fields

Convert Bit-field to list in python


I'm not a dev... And wouldlike a function, to convert a bit value, into a list of integer :

let say I have the following possible bits : 1 2 4 8

I would like a function, bit2list(7) that would give back (1;2;4) or bit2list(9) should give back (1;8)

Can someone Help ?


Solution

  • A good starting point would be the bin function:

    >>> bin(7)
    '0b111'
    >>> bin(9)
    '0b1001'
    

    From there, it's pretty easy to transform the bit strings into the indices you want.