You need to make the initial bit into the type unsigned long long
(or uint64_t
) so that it doesn't overflow when bitshifted.
mask = ((1ULL << (high - low + 1)) - 1) << low;
^^^
For number 1 of int
type, it'll overflow when leftshifted for 32 bits:
((1 << (high-low + 1))-1) // Where (high-low + 1) == 31 - 0 + 1 == 32
^
00000000 00000000 00000000 00000001 = 1
v <-- Left shift for 32 bits --------<
(1) 00000000 00000000 00000000 00000000 = 0
But that would work for a 64-bit integer type. So change it to 1ULL
and the problem is gone.