I’ve seen two different ways to approach combining bit shifting and masking, and was wondering if they were equivalent assuming the result is used as a boolean or if one had less issues or better performance than the other.
The two:
flags & (BIT_MASK << BIT_NUMBER)
or
(flags >> BIT_NUMBER) & BIT_MASK
The former seems like it might have issues on some platforms depending on the size of flags, i.e. the bit shift might push the mask out the top of the temporary variable. Is this an issue? Are there any performance differences in up-shifting versus down-shifting?
Combining BIT_MASK and BIT_NUMBER into a single unambiguous mask strikes me as better again, but I’m working with legacy code that I want to minimize changes to.
If
BIT_MASKandBIT_NUMBERare constants, the compiler will probably precalculate the expression and save an instruction if you group them together. This favors the first approach.If you’re trying to get more than one bit you will want to shift the result to the right. This favors the second approach.