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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,872 questions

51,796 answers

573 users

How to use BitArray to set and find set bits indexes in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections

Class BitArrayDemo
    Public Shared Sub Main()
        Dim bits As BitArray = New BitArray(16)

        ' Set bits at positions 3, 5, 11, and 14
        bits.Set(3, True)
        bits.Set(5, True)
        bits.Set(11, True)
        bits.Set(14, True)

        ' Print binary representation
        Console.WriteLine(GetBinaryString(bits))

        ' Find and print the first set bit
        Dim firstSetBit As Integer = FindFirstSetBit(bits)
        Console.WriteLine("First set bit at index: " & firstSetBit)

        ' Print all set bit indexes
        Console.WriteLine("All the set bits indexes:")
        PrintSetBitIndexes(bits)
    End Sub

    ' Converts BitArray to binary string from highest to lowest bit
    Private Shared Function GetBinaryString(ByVal bits As BitArray) As String
        Dim binary As Char() = New Char(bits.Count - 1) {}

        For i As Integer = bits.Count - 1 To 0 Step -1
            binary(bits.Count - 1 - i) = If (bits(i), "1"c, "0"c)
        Next

        Return New String(binary)
    End Function

    ' Finds the first set bit (lowest index with True)
    Private Shared Function FindFirstSetBit(ByVal bits As BitArray) As Integer
        For i As Integer = 0 To bits.Count - 1
            If bits(i) Then Return i
        Next
        Return -1
    End Function

    ' Prints all indexes of bits that are set to True
    Private Shared Sub PrintSetBitIndexes(ByVal bits As BitArray)
        For i As Integer = 0 To bits.Count - 1
            If bits(i) Then Console.Write(i & " ")
        Next
        Console.WriteLine()
    End Sub
End Class

 
 
' run:
' 
' 0100100000101000
' First set bit at index: 3
' All the set bits indexes:
' 3 5 11 14 
' 

 



answered Nov 3, 2025 by avibootz
...