组合位标志 [英] Combine Bitflags

查看:88
本文介绍了组合位标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个标志:

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

我想创建一个函数,在其中输入某个标志,可以说:6.

I want to create a function where I input a certain flag, lets say : 6.

从2开始,返回的应该是HDDT. 4 = 6. 也可能会组合3个或更多标志或仅将一个标志组合在一起. 例如:7 = 1 | 2 | 4 => HRHDDT.

Returned should be HDDT, since 2 | 4 = 6. It can also happen that 3 or more flags are combined or just a single one. e.g. : 7 = 1 | 2 | 4 => HRHDDT.

如何根据标志值返回缩进的字符串?

How can I return the concated string depending on the flag value?

在我的情况下,枚举还有很多条目,这会使if语句变得非常不舒服,因为我必须涵盖数百种情况.

In my case the enum has many more entries, which would make a simple if statement really uncomfortable, because I would have to cover hundreds of cases.

对此有什么聪明的解决方案吗?

Is there any clever solution to this?

推荐答案

您可以像这样将标志存储为dict:

You can store the flags as a dict like so:

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

,然后按位and用带有标志的数字检索字符串:

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'

这篇关于组合位标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆