using System;
using System.Numerics; // Provides BitOperations.TrailingZeroCount
class Program
{
/*
FindNthSetBit32:
----------------
Given:
- x : a 32-bit unsigned integer
- n : which set bit to find (1-based index)
Returns:
A 32-bit mask with ONLY the Nth set bit of x turned on.
If n is larger than the number of set bits, returns 0.
Algorithm:
- Use BitOperations.TrailingZeroCount(x) to locate the lowest set bit.
- Remove that bit using x &= (x - 1).
- When we reach the Nth one, return 1u << index.
Notes:
- TrailingZeroCount(x) is extremely efficient and maps to a single CPU instruction.
- C# treats uint as a true 32-bit unsigned integer, ideal for bit manipulation.
*/
static uint FindNthSetBit32(uint x, uint n)
{
while (x != 0)
{
// Index (0–31) of the lowest set bit
int index = BitOperations.TrailingZeroCount(x);
// If this is the Nth set bit, return mask
if (--n == 0)
return 1u << index;
// Remove the lowest set bit
x &= (x - 1);
}
// Fewer than n set bits
return 0;
}
// Convert a 32-bit integer to a padded binary string
static string ToBinary32(uint x)
{
string s = Convert.ToString(x, 2);
return new string('0', 32 - s.Length) + s;
}
static void Main()
{
uint value = 0b00001101001101101100100010100000u;
uint n = 4;
uint result = FindNthSetBit32(value, n);
Console.WriteLine("Input value: " + ToBinary32(value));
Console.WriteLine("N = " + n);
Console.WriteLine("Result mask: " + ToBinary32(result));
}
}
/*
run:
Input value: 00001101001101101100100010100000
N = 4
Result mask: 00000000000000000100000000000000
*/