Combine Bit Flags

I have a few flags:

    None = 0
    HR = 1
    HD = 2,
    DT = 4,
    Fl = 8
..

etc.

I want to create a function in which I enter some flag, say: 6.

The return must be HDDT, since 2 | 4 = 6. It can also happen that three or more flags are combined or just one. for example: 7 = 1 | 2 | 4 => HRHDDT.

How to return a completed string depending on the flag value?

In my case, the enumeration has much more entries, which would make the simple expression really uncomfortable, because I would have to cover hundreds of cases.

Is there any smart solution?

+4
source share
2 answers

You can store flags like dictthis:

flags = {1:'HR', 2:'HD', 4:'DT', 8:'FL'}

and bit-wise andyour number with flags for extracting strings:

def get_flags(num):
    if num:
        return ''.join(flags[x] for x in flags if x & num)
    return None

>>> get_flags(6)
'HDDT'
+1

, - :

flags = ['HR','HD','DT','Fl']

:

def power2():
    i = 1
    while True:
        yield i
        i *= 2

def obtain_flag(val):
    if val:
        return ''.join([f for f,i in zip(flags,power2()) if i&val])
    else:
        return None

return None : , .

, ( ):

def obtain_flag(val):
    if val:
        return [f for f,i in zip(flags,power2()) if i&val]

:

>>> obtain_flag(6)
'HDDT'
>>> obtain_flag(7)
'HRHDDT'
>>> obtain_flag(0) # returns None, but None is not printed
>>> obtain_flag(1)
'HR'
>>> obtain_flag(2)
'HD'
>>> obtain_flag(3)
'HRHD'
>>> obtain_flag(4)
'DT'
+2

Source: https://habr.com/ru/post/1677699/


All Articles