测试位掩码是否只有一个标志 [英] Testing if a bitmask has one and only one flag
问题描述
我一直在搜寻google和堆栈溢出来寻找该问题的答案,但我一直无法明确找到它.
I've been scouring google and stack overflow for an answer to this question and I haven't been able to explicitly find it.
我将如何测试位掩码以查看其是否设置了一个且仅设置了一个标志? I.E如果在掩码中设置了其他任何标志,它将返回false吗?
我知道我可以检查一下面具是否有任何标志.
I know that I can check to see if the mask has any flags with this.
(currentFlags & state) == state
我认为检查掩码是否只有一个标志要复杂一些.我访问过的每个站点(解释位屏蔽)都具有典型的添加/删除/等内容,但从未提及单数检查.
I figure it's a bit more complex to check if a mask only has one flag. Every site that I've visited, that explains bitmasking, has the typical add/remove/etc but never mentions a singular check.
我确实在SE上看到了该线程. 形成和检查位掩码的方法我不确定该掩码和魔术是否有效事情就是我一直在寻找的,如果是的话,我对它的用法有些迷惑.
I did see this thread on SE. Methods to form and check bitmasks I wasn't sure if this mask and magic thing was what I was looking for, and if it was, I'm a little lost on how it's used.
推荐答案
如果仅是单个标志,则==
运算符就足够了,因为您确切知道要查找的值.因此,在您的情况下:
If it's only a single flag then ==
operator is sufficient as you know exactly what value you're looking for. So in your case:
currentFlags == state
会做这份工作.
如果要检查是否设置了多个标志(特殊组合),可以使用|=
运算符构建一个值,然后使用==
进行比较.
If you'd like to check if there are multiple flags set (particular combination) you could build a value using |=
operator and then compare it using ==
.
这篇关于测试位掩码是否只有一个标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!