1

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.

Community
  • 1
  • 1
steve
  • 301
  • 2
  • 10

2 Answers2

2

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

blazejmar
  • 1,080
  • 8
  • 10
  • It didn't even dawn on me to try the == operator. Sometimes the most elegant solutions are the simplest. Thank you! – steve Jul 17 '14 at 18:12
2

For those who stumble across this expecting the "one and only one" to refer to checking that you have "only one flag, but not any one specific flag" set on an integer:

(currentFlags & (currentFlags - 1)) == 0