Combine Bitflags

允我心安 提交于 2019-12-05 09:56:13

You can store the flags as a dict like so:

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

and bit-wise and your number with the flags to retrieve the strings:

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

>>> get_flags(6)
'HDDT'

Let's assume we have a list somewhere with the powers of two:

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

Then you can write the following function:

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

The return None is not necessary: it is the flag that maps to zero.

Or if you want a list of the flags (in that case the flags can be anything):

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

This gives:

>>> 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'
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!