Jake Freelander
Jake Freelander

Reputation: 1471

Checking for bit flags

I'm trying to check for a bit in a flags value of which flags can be |'d together. So far i'm using this

 if ((someclass.flags | CONST_SOMEFLAG) == someclass.flags)

to check if its true or false but is there a more "elegant" way of doing this?

Upvotes: 2

Views: 7740

Answers (3)

datenwolf
datenwolf

Reputation: 162297

What you want to know is, if the flag bit is set among all the other possibly set or unset bits. The canonical way to do this, is to bitwise and (&) test for being nonzero

if( someclass.flags & CONST_SOMEFLAG )

Upvotes: 0

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13196

That will work fine, but it's more conventional to use &:

if (flags & MASK) . . .

This is likely because on some processors testing a register for != 0 is faster than testing for equality with a stored value.

Upvotes: 0

András Aszódi
András Aszódi

Reputation: 9690

Use bitwise OR to set the flags, use bitwise AND to test, like this:

if (someclass.flags & CONST_SOMEFLAG) ...

Upvotes: 2

Related Questions