如何使用带有位标志的枚举
我有一个使用位标志的枚举声明,但我无法确切地弄清楚如何使用它。
enum
{
kWhite = 0,
kBlue = 1 << 0,
kRed = 1 << 1,
kYellow = 1 << 2,
kBrown = 1 << 3,
};
typedef char ColorType;
我想在一个 colorType
中存储多种颜色,我应该将这些位OR
放在一起吗?
ColorType pinkColor = kWhite | kRed;
但是假设我想检查 pinkColor
是否包含 kRed
,我该怎么做?
有人愿意给我一个使用提供的 ColorType
示例的示例吗?
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;
I suppose to store multiple colors in one colorType
I should OR
the bits together?
ColorType pinkColor = kWhite | kRed;
But suppose I would want to check if pinkColor
contains kRed
, how would I do this?
Anyone care to give me an example using the provided ColorType
example ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,使用按位或 (
|
) 设置多个标志:然后使用按位与 (
&
) 测试是否设置了标志:& 的结果仅当两个操作数中设置了相同的位时,
才会设置任何位。由于 kRed 中唯一的位是位 1,因此如果其他操作数也没有设置该位,则结果将为 0。如果您需要了解特定标志是否设置为
BOOL
,而不是立即在if
条件下测试它,请将按位 AND 的结果与测试位进行比较:Yes, use bitwise OR (
|
) to set multiple flags:Then use bitwise AND (
&
) to test if a flag is set:The result of
&
has any bit set only if the same bit is set in both operands. Since the only bit inkRed
is bit 1, the result will be 0 if the other operand doesn't have this bit set too.If you need to get whether a particular flag is set as a
BOOL
rather than just testing it in anif
condition immediately, compare the result of the bitwise AND to the tested bit: