使用位运算符的标志 [英] Using Bitwise operators on flags

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

问题描述

我有四个标志

Current = 0x1  
Past = 0x2  
Future = 0x4  
All = 0x7

说我收到这两个标志的过去与未来( setFlags(PAST |未来))。我怎样才能知道,如果是吗?同样,我怎么能告诉电流是不是在里面?这样,我就不必测试各种可能的组合。

Say I receive the two flags Past and Future (setFlags(PAST | FUTURE)). How can I tell if Past is in it? Likewise how can I tell that Current is not in it? That way I don't have to test for every possible combination.

推荐答案

如果你想在测试屏蔽所有位匹配:

If you want all bits in the test mask to match:

if((value & mask) == mask) {...}

如果你想在测试规则的任何一位来匹配:

If you want any single bit in the test mask to match:

if((value & mask) != 0) {...}

的区别是最明显的,当你正在测试多种事物的价值。

The difference is most apparent when you are testing a value for multiple things.

要测试排除:

if ((value & mask) == 0) { }

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

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