How can I optimise this bitmask generation algorithm?
You can compute a power of 2 using the operation of left shift, in C and related languages &lt;&lt;. For example, $2^n$ is the same as 1 &lt;&lt; n.

An alternative is to precompute the mask for all possible input values, and store them in the array. You'll have to try it out to see whether this is faster than the other suggestion.