如何使用带有位标志的枚举 [英] How to use enums with bit flags

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

问题描述

我有一个使用位标志的枚举声明,但我不知道如何使用它.

I have an enum declaration using bit flags and I cant exactly figure out on how to use this.

enum 
{
  kWhite   = 0,
  kBlue    = 1 << 0,
  kRed     = 1 << 1,
  kYellow  = 1 << 2,
  kBrown   = 1 << 3,
};
typedef char ColorType;

我想在一个 colorType 中存储多种颜色,我应该将这些位OR 放在一起吗?

I suppose to store multiple colors in one colorType I should OR the bits together?

ColorType pinkColor = kWhite | kRed;

但是假设我想检查 pinkColor 是否包含 kRed,我该怎么做?

But suppose I would want to check if pinkColor contains kRed, how would I do this?

有人愿意用所提供的 ColorType 示例给我一个示例吗?

Anyone care to give me an example using the provided ColorType example ?

推荐答案

是的,使用按位 OR (|) 设置多个标志:

Yes, use bitwise OR (|) to set multiple flags:

ColorType pinkColor = kWhite | kRed;

然后使用按位与 (&) 来测试是否设置了标志:

Then use bitwise AND (&) to test if a flag is set:

if ( pinkColor & kRed )
{
   // do something
}

& 的结果只有在 两个 操作数中设置了相同的位时才会设置任何位.由于 kRed 中唯一的位是位 1,如果另一个操作数也没有设置该位,则结果将为 0.

The result of & has any bit set only if the same bit is set in both operands. Since the only bit in kRed is bit 1, the result will be 0 if the other operand doesn't have this bit set too.

如果您需要获取特定标志是否设置为 BOOL 而不是立即在 if 条件下测试它,请将按位 AND 的结果与测试位:

If you need to get whether a particular flag is set as a BOOL rather than just testing it in an if condition immediately, compare the result of the bitwise AND to the tested bit:

BOOL hasRed = ((pinkColor & kRed) == kRed);

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

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