using System;
using System.Numerics;
class FindNthSetBit64Program
{
/*
findNthSetBit64:
----------------
Given:
- x : a 64-bit unsigned integer (ulong)
- n : which set bit to find (1-based index)
Returns:
A 64-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 1UL << index.
Notes:
- TrailingZeroCount maps to a single CPU instruction.
- ulong is a true 64-bit unsigned integer.
*/
static ulong FindNthSetBit64(ulong x, int n)
{
while (x != 0UL) {
// Index (0–63) of the lowest set bit
int index = BitOperations.TrailingZeroCount(x);
n--;
if (n == 0)
return 1UL << index;
// Remove the lowest set bit
x &= (x - 1UL);
}
// Fewer than n set bits
return 0UL;
}
/*
ToBinary64:
-----------
Convert a 64-bit integer to a padded 64-bit binary string.
*/
static string ToBinary64(ulong x)
{
string s = Convert.ToString((long)x, 2);
return s.PadLeft(64, '0');
}
static void Main()
{
ulong value =
0b0000000000000000000010000000000000001101001101101100100010100000UL;
int n = 4;
ulong result = FindNthSetBit64(value, n);
Console.WriteLine("Input value: " + ToBinary64(value));
Console.WriteLine("N = " + n);
Console.WriteLine("Result mask: " + ToBinary64(result));
}
}
/*
run:
Input value: 0000000000000000000010000000000000001101001101101100100010100000
N = 4
Result mask: 0000000000000000000000000000000000000000000000000100000000000000
*/