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 by avibootz

Related questions

1 answer 16 views
1 answer 10 views
1 answer 14 views
1 answer 13 views
2 answers 19 views
...