I have seen two kinds of bit masking implementations:
- The one that uses bitwise shift operator to set
flags |= 1 << MASK_VALUE
and clear the maskflags &= ~(1 << MASK_VALUE)
. This is the approach that is used most frequently. - The other one doesn't use bitwise shift operator and only uses logical operators to set
flags |= MASK_VALUE
and clear the maskflags &= ~(MASK_VALUE)
#define MASK_VALUE 4
int flags = 0;
flags |= 1 << MASK_VALUE;
printf("flags |= 1 << MASK_VALUE: %d\n", flags);
flags &= ~(1 << MASK_VALUE);
printf("flags &= ~(1 << MASK_VALUE): %d\n", flags);
flags |= MASK_VALUE;
printf("flags |= MASK_VALUE: %d\n", flags);
flags &= ~(MASK_VALUE);
printf("flags &= ~(MASK_VALUE): %d\n", flags);
outputs
flags |= 1 << MASK_VALUE: 16
flags &= ~(1 << MASK_VALUE): 0
flags |= MASK_VALUE: 4
flags &= ~(MASK_VALUE): 0
Is there any reason to use bitwise shift operator? Is the first approach preferable over the second one?