Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

How to find the Nth set bit in a 64‑bit integer with VB.NET

1 Answer

0 votes
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
'

 



answered Jul 25 by avibootz
...