问题
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