Testing if a bitmask has one and only one flag

与世无争的帅哥 提交于 2019-12-11 11:47:39

问题


I've been scouring google and stack overflow for an answer to this question and I haven't been able to explicitly find it.

How would I test a bitmask to see if it has one and ONLY one flag set to it? I.E It would return false if any other flags were set inside the mask?

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.

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.


回答1:


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

would do the job.

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 ==.



来源:https://stackoverflow.com/questions/24807995/testing-if-a-bitmask-has-one-and-only-one-flag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!