Assuming a two's complement signed 32-bit integer called number is the input (hence only counting bits 0 to 30 in the for loop):
int number = (1 << 3) | 1; // this is the input, it can be whatever you like
int currentLsbCount = 0;
int desiredLsbCount = 2; // this is your n
int foundLsb = 0;
int foundLsbIndex = 0;
for (int i = 0; i < 31; i++)
{
int bit = (number >> i) & 1;
if (bit == 1)
{
++currentLsbCount;
}
if (currentLsbCount == desiredLsbCount)
{
foundLsb = number & (1 << i);
foundLsbIndex = i;
break;
}
}
foundLsb will hold the value or will be zero if the input was zero; foundLsbIndex will hold the index of the bit.
As far as I know you would have to iterate. There is no quicker method than looping through the bits. You could add some skip logic in, but it would not improve the worst case timing. For instance:
if ((number & ((1 << x) - 1)) == number)
{
// the bottom x bits are zero...
}
This would increase the number of operations for the worst case.