How do you check whether the 5th bit and the 2nd bit of the same number are the same? (In C programming)
How do you check whether the 5th bit and the 2nd bit of the same number are the same?
Collapse
X
-
Tags: None
-
Bit mask only the 5th bit and the 2nd bit? But how do you compare these two bits if they are part of the same number?Comment
-
If the bits are equal to each other then they must either all be equal to 0 or all be equal to 1. The following C code works for comparing any number of bits.
By the way, it is usually safer to use an unsigned type when working with individual bits.Code:#include <stdbool.h> bool isMatchingBits(unsigned long value, unsigned long mask) { const unsigned long isolatedBits = value & mask; return ((isolatedBits == 0uL) || (isolatedBits == mask)); }Comment
Comment