Imports System
Module FindNthSetBit32
'
' CountTrailingZeros:
' -------------------
' Returns the number of trailing zeros in a 32‑bit integer.
' Equivalent to C++ std::countr_zero or GCC __builtin_ctz.
' Assumes x <> 0.
'
Function CountTrailingZeros(x As UInteger) As Integer
Dim i As Integer = 0
' Scan upward from the least significant bit
While (x And 1UI) = 0UI
x >>= 1
i += 1
End While
Return i
End Function
'
' 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 CountTrailingZeros(x) to locate the lowest set bit.
' - Remove that bit using x = x And (x - 1).
' - When we reach the Nth one, return 1 << index.
'
Function FindNthSetBit32(x As UInteger, n As Integer) As UInteger
While x <> 0UI
' Index (0–31) of the lowest set bit
Dim index As Integer = CountTrailingZeros(x)
' If this is the Nth set bit, return mask
n -= 1
If n = 0 Then
Return 1UI << index
End If
' Remove the lowest set bit
x = x And (x - 1UI)
End While
' Fewer than n set bits
Return 0UI
End Function
'
' ToBinary32:
' -----------
' Convert a 32-bit integer to a padded binary string.
'
Function ToBinary32(x As UInteger) As String
Dim s As String = Convert.ToString(x, 2)
Return New String("0"c, 32 - s.Length) & s
End Function
Sub Main()
Dim value As UInteger = &B00001101001101101100100010100000UI
Dim n As Integer = 4
Dim resultMask As UInteger = FindNthSetBit32(value, n)
Console.WriteLine("Input value: " & ToBinary32(value))
Console.WriteLine("N = " & n)
Console.WriteLine("Result mask: " & ToBinary32(resultMask))
End Sub
End Module
'
' run:
'
' Input value: 00001101001101101100100010100000
' N = 4
' Result mask: 00000000000000000100000000000000
'