using System;
using System.Collections;
class BitArrayDemo
{
static void Main()
{
// Create a BitArray with 16 bits, all initialized to false (0)
BitArray bits = new BitArray(16);
// Set bits at positions 3, 5, 11, and 14 to true (1)
bits.Set(3, true);
bits.Set(5, true);
bits.Set(11, true);
bits.Set(14, true);
// Print the BitArray as a binary string
Console.WriteLine(GetBinaryString(bits));
// Find and print the first set bit
int firstSetBit = FindFirstSetBit(bits);
Console.WriteLine("First set bit at index: " + firstSetBit);
// Print all set bit indexes
Console.WriteLine("All the set bits indexes:");
PrintSetBitIndexes(bits);
}
// Method to convert BitArray to binary string
static string GetBinaryString(BitArray bits) {
char[] binary = new char[bits.Count];
for (int i = bits.Count - 1; i >= 0; i--) {
binary[bits.Count - 1 - i] = bits[i] ? '1' : '0';
}
return new string(binary);
}
static int FindFirstSetBit(BitArray bits) {
for (int i = 0; i < bits.Count; i++) {
if (bits[i]) return i;
}
return -1; // No bits set
}
static void PrintSetBitIndexes(BitArray bits) {
for (int i = 0; i < bits.Count; i++) {
if (bits[i]) Console.Write(i + " ");
}
Console.WriteLine();
}
}
/*
run:
0100100000101000
First set bit at index: 3
All the set bits indexes:
3 5 11 14
*/