In this case the mask isn't needed. There are cases when you want to mask bits, but there is no sense in masking bits that are going to be shifted away. As long as you're using unsigned
for bitwise operations, you're fine.
But since we're mentioning unsigned
, keep in mind that all types smaller than int
will be promoted to int
for bitwise and arithmetic operations, and signed int
kinda sucks. Left shifting a signed int
which would lead to an overflow is undefined behavior. Right shifting will usually be implemented as an aritmetic shift (implementation dependant -- but usually it will repeat the sign bit when right-shifting), and this can surprise people at times:
uint16_t x = 0xF123;
uint32_t y = (x << 16) >> 16; // implementation-dependant, but likely 0xFFFFF123
uint32_t z = (x << 28); // undefined behavior