Sorry if this is a beginner question - my experience with bitfields is zero. I have a series of 25 flags represented by Bitfields and an session integer which represents any flags set at this time. I want to mask the integer e.g. 268698112 and see what flags are set.
class Flags:
flaga = 0x0001
flagi = 0x0100
flagp = 0x8000
flagq = 0x010000
flagv = 0x10000000
I have tried the following two lines but they only return zero.
test_a = session & flag_mask
test_b = (session >> flag_mask) & 1
I have looked at Extract bitfields from an int in Python and although I can see Bitstrings might be helpful I cannot see how to then add the integer into the mix without getting an error for example I have tried:
bitstring.Bits(session) & bitstring.BitArray(flag_mask)
(bitstring.Bits(session) >> bitstring.BitArray(flag_mask)) & 1
but get
Bitstrings must have the same length for and operator
< not supported between instances of "BitArray" and "int"
How can I extract true or false values from the session int for the given flags?
SOLUTION
So I actually have the solution above but with 25 possible flags I just didn't have the confidence to check all of them and realise so. The following function returns a list of set flags.
def decode_flags(flagcode, flagObject):
flags = [a for a in dir(flagObject) if not a.startswith('__')]
enabled_flags = []
for attr in flags:
flag_mask = (getattr(flagObject, attr))
if flagcode & flag_mask:
enabled_flags.append(attr)
Docs for IntFlag and Flag
I know you have a solution, but still wanted to share how to use IntFlag for this. I used your example value of
268698112(0b10000000001000000001000000000).Create an IntFlag class with your flags:
To convert an
intpass it to the constructor.IntFlag does not discard undefined flags, but they are returned all as one int "remainder".
Remainder
262656is0b1000000001000000000, so two undefined flags.Get defined flags as list:
Check flags: