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
'