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

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

问题描述

我有一个枚举声明使用位标志,我不能精确地找出如何使用这个。

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 我应该位一起?

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 example?

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

推荐答案

> | )设置多个标志:

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

ColorType pinkColor = kWhite | kRed;

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

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 ,而不是只是在中测试条件立即,将按位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天全站免登陆