How to create a bitset in C#

1 Answer

0 votes
using System;
using System.Collections;

class Program
{
    static void Main()
    {
        // Create a BitArray with a size of 8 bits
        BitArray bitArray = new BitArray(8);

        // Set some bits
        bitArray[0] = true;  // Set the first bit
        bitArray[3] = true;  // Set the fourth bit

        // Print the BitArray
        Console.WriteLine("BitArray:");
        PrintBitArray(bitArray);

        bitArray.SetAll(false);  // Set all bits to false
        bitArray.Set(2, true);   // Set the third bit to true

        // Print the modified BitArray
        Console.WriteLine("Modified BitArray:");
        PrintBitArray(bitArray);
    }

    static void PrintBitArray(BitArray bitArray) {
        for (int i = 0; i < bitArray.Length; i++) {
            Console.Write(bitArray[i] ? "1" : "0");
        }
        Console.WriteLine();
    }
}



/*
run:
 
BitArray:
10010000
Modified BitArray:
00100000
 
*/

 



answered May 7, 2025 by avibootz

Related questions

1 answer 148 views
1 answer 245 views
245 views asked May 7, 2025 by avibootz
1 answer 223 views
1 answer 236 views
236 views asked May 7, 2025 by avibootz
1 answer 275 views
275 views asked May 7, 2025 by avibootz
2 answers 289 views
2 answers 234 views
...