I'm wondering if there is an efficient algorithm implementation for the following problem:
Given an unsigned integer U, make a mask that selects the first N bits of U that are set. (Going from right to left, low order to high order)
So for example:
f(U=1111, N=2) -> 0011
f(U=1010, N=2) -> 1010
f(U=1110, N=2) -> 0110
f(U=0111, N=2) -> 0011
f(U=0011, N=2) -> 0011
Most processors have a "find first set bit" or similar instruction, so I figure in the worst case I can invoke that N times, but is it possible to do better?