I have two bit maps and I need to check if a value is in one of them. Do I need to check on both, or can I add them and do the check once?
Asked
Active
Viewed 77 times
1
-
3Use XOR ^ and mask for the bit or bits that you want to check – Hans Mar 22 '17 at 13:32
1 Answers
1
Depends on what you mean with "add". I assume you mean a bitwise OR
const unsigned char map = map1 | map2;
It is clear, that if a bit is set in one of the maps, it will be also set in the final map
. However, I cannot give advise which version is faster, doing the bitwise OR and check then
bool bitIsSet = (map1 | map2) & maskForBit;
or to check against both and use the logical OR
bool bitIsSet = (map1 & maskForBit) || (map2 & maskForBit);
But I suppose it will not be a crucial point in your application in respect of speed (otherwise test it!). It seems more to be an issue of taste or what you can read/understand better/faster.
Edit
The comment of Hans just reminds me, that you could also mean that the bit should be set in one map exclusively. In this case just exchange the bitwise OR with the bitwise XOR in the first case and the logical OR by a not equal !=
in the second case.

marlam
- 590
- 5
- 14