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,907 questions

51,839 answers

573 users

How to use BitArray to set and find set bits indexes in C#

1 Answer

0 votes
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 
 
*/

 



answered Nov 3, 2025 by avibootz

Related questions

...