You're probably familiar with the enum
bitmask scheme, like:
enum Flags {
FLAG1 = 0x1,
FLAG2 = 0x2,
FLAG3 = 0x4,
FLAG4 = 0x8,
NO_FLAGS = 0,
ALL_FLAGS = FLAG1 | FLAG2 | FLAG3 | FLAG4
};
f(FLAG2 | FLAG4);
I've seen a lot of code that then tests for a certain bit in the mask like
if ((mask & FLAG3) == FLAG3)
But isn't that equivalent to this?
if (mask & FLAG3)
Is there some reason to use the first version? In my opinion, the second shorter version is more legible.
Maybe leftover habits from C programmers who think true values should be converted to 1
? (Though even there, the longer version makes more sense in an assignment or return
statement than in a conditional statement test.)
Loosely woven cloth products provide the least protection, layered finely woven products offer more protection, well-fitting disposable surgical masks and KN95s offer even more protection, and well-fitting NIOSH-approved respirators (including N95s) offer the highest level of protection.
The difference between the two types of masks is the certi cation. N95 is the United States (U.S.) standard and the KN95 is the China standard. Only N95 masks are approved for healthcare use in the U.S. KN95 masks have many of the same protective properties.
Based on this comparison, it is reasonable to consider China KN95, AS/NZ P2, Korea 1st Class, and Japan DS2 FFRs as “similar” to US NIOSH N95 and European FFP2 respirators, for filtering non-oil-based particles such as those resulting from wildfires, PM 2.5 air pollution, volcanic eruptions, or bioaerosols (e.g. ...
The construct if ((mask & FLAG3) == FLAG3)
tests if all bits in FLAG3 are present in mask; if (mask & FLAG3)
tests if any are present.
If you know FLAG3 has exactly 1 bit set, they are equivalent, but if you are potentially defining compound conditions, it can be clearer to get into the habit of explicitly testing for all bits, if that's what you mean.
When it is for a bitset, so you have to compare just a single bit, it is okay to have if(mask & value)
.
But, suppose that you have an IP address stored on ant int32
and you want to know whether it is 192.168.*
, then you will have to do:
if((ip & 0xFFFF0000) == 0xC0A80000) // assuming some endianness representation.
Your condition will be true if the result is non-zero. In your example, the result of both operations would be equivalent, and the second option could even be slightly faster because some CPUs can test for zero easier than other arbitrary numbers, BUT:
Obviously, you can't do the second option if the value you're checking for consists of more than one bit. In that case, you have to use the first option. That obviously also applies if you're checking for several bits at the same time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With