Imports System
Imports System.Numerics
Module 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 And (x - 1).
' - When we reach the Nth one, return 1UL << index.
'
Function findNthSetBit64(ByVal x As ULong, ByVal n As Integer) As ULong
While x <> 0UL
' Index (0–63) of the lowest set bit
Dim index As Integer = BitOperations.TrailingZeroCount(x)
n -= 1
If n = 0 Then
Return 1UL << index
End If
' Remove the lowest set bit
x = x And (x - 1UL)
End While
' Fewer than n set bits
Return 0UL
End Function
'
' toBinary64:
' -----------
' Convert a 64-bit integer to a padded 64-bit binary string.
'
Function toBinary64(ByVal x As ULong) As String
Dim s As String = Convert.ToString(CLng(x), 2)
Return s.PadLeft(64, "0"c)
End Function
Sub Main()
Dim value As ULong =
&B0000000000000000000010000000000000001101001101101100100010100000UL
Dim n As Integer = 4
Dim result As ULong = findNthSetBit64(value, n)
Console.WriteLine("Input value: " & toBinary64(value))
Console.WriteLine("N = " & n)
Console.WriteLine("Result mask: " & toBinary64(result))
End Sub
End Module
'
' run:
'
' Input value: 0000000000000000000010000000000000001101001101101100100010100000
' N = 4
' Result mask: 0000000000000000000000000000000000000000000000000100000000000000
'