C# Bit array (BitArray)

C# collections

BitArray is a collection in C# used to represent a set of bit values.

BitArray belongs to the System.Collections namespace and is mainly used for processing binary data or performing bit operations.

Compared to using a Boolean array (bool[]), BitArray is more efficient because it stores each bit in a compact way.

The BitArray class manages a compact array of bit values, represented using Boolean values.

true means the bit is on (1), false means the bit is off (0)。

When you need to store bits but do not know the number of bits in advance, use a BitArray.

You can useInteger IndexAccess items from the BitArray collection, with the index starting from zero.

Methods and properties of the BitArray class

The table below listsBitArraySome commonly used ones of the classProperty:

Attribute NameTypeDescription
CountintGetBitArrayThe number of bits contained (read-only).
LengthintGet or setBitArrayThe number of bits in (supports dynamic resizing).
IsReadOnlyboolGets a value indicating whether theBitArrayis read-only (alwaysfalse)。
SyncRootobjectGets an object used to synchronize access to theBitArrayaccess.
IsSynchronizedboolGets a value indicating whether access to theBitArrayis synchronized (thread-safe).
Item[int index]boolGets or sets the value of the bit at the specified index (accessed via the indexer).

Property access:

BitArray bits = new BitArray(8); // 创建 8 位的 BitArray,所有位默认为 false
Console.WriteLine(bits.Length); // 输出:8
bits.Length = 10; // 修改长度为 10,新增的位默认为 false

The table below listsBitArraySome commonly used ones of the classMethods:

Method NameReturn TypeDescription
And(BitArray)BitArrayBitwise AND operation, on twoBitArrayperforms an AND operation on the corresponding bits, modifies the current instance in place and returns the current instance itself.
Or(BitArray)BitArrayBitwise OR operation, on twoBitArrayperforms an OR operation on the corresponding bits, modifies the current instance in place and returns the current instance itself.
Xor(BitArray)BitArrayBitwise XOR operation, on twoBitArrayperforms an XOR operation on the corresponding bits, modifies the current instance in place and returns the current instance itself.
Not()BitArrayBitwise NOT operation, which inverts each bit of the current instance, modifies it in place and returns the current instance itself.
Set(int index, bool value)voidSets the bit at the specified index to the specified value (trueorfalse)。
SetAll(bool value)voidSets all bits to the specified value (trueorfalse)。
Get(int index)boolGets the value of the bit at the specified index.
Clone()objectCreate currentBitArrayA shallow copy (duplicate) of.
CopyTo(Array array, int index)voidwillBitArrayCopies the contents to the specified array, starting at the specified index.
Equals(object obj)boolDetermines whether the specified object is equal to the currentBitArray。
GetEnumerator()IEnumeratorReturns an enumerator that iterates throughBitArraythe bit in.

Method usage:

BitArray bits = new BitArray(8, false); // 创建 8 位的 BitArray,初始值全部为 false
bits.Set(0, true); // 设置第 0 位为 true
Console.WriteLine(bits.Get(0)); // 输出:True
bits.SetAll(true); // 将所有位设置为 true

Example

The following example demonstrates the use of BitArray:

In BitArrayIndex 0 corresponds to the least significant bit of a binary numberThe bit string obtained by traversing in forward index order is opposite to the normal writing order; therefore, the following example uses reverse traversal for output.

Methods such as And(), Or(), Xor() willIn-place modificationThey call the instance and return itself, so a copy constructor is used before each operation.new BitArray(ba1)Create a copy.

Comparison of two bit orders for the value 13
Usual writing order (high-order first):
0
Bit 7
0
Bit 6
0
Bit 5
0
Bit 4
1
Bit 3
1
Bit 2
0
Bit 1
1
Bit 0
BitArray indexing order (index 0 corresponds to the least significant bit):
1
index 0
0
index 1
1
Index 2
1
Index 3
0
Index 4
0
Index 5
0
Index 6
0
Index 7
sameavalue 13,pressIndexcorrectsequencetraversal BitArray We getis 1 0 1 1 0 0 0 0, andday常书writeSequencecorrectOK相反, thereforein the example采use逆towardtraversalOutput。

Example

using System;
using System.Collections;

namespace CollectionsApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize two BitArrays to store binary bits
            BitArray ba1 = new BitArray(new byte[] { 60 }); // 60 = 00111100
            BitArray ba2 = new BitArray(new byte[] { 13 }); // 13 = 00001101

            // Output the contents of ba1 and ba2
            Console.WriteLine("Bit array ba1 (60):");
            PrintBitArray(ba1);

            Console.WriteLine("Bit array ba2 (13):");
            PrintBitArray(ba2);

            // Perform AND operation and output the result
            // And/Or/Xor modify the instances that call them in place; create a copy of ba1 before the operation.
            BitArray baAnd = new BitArray(ba1);
            baAnd.And(ba2); // 60 & 13 = 12
            Console.WriteLine("Bit array after AND operation (12):");
            PrintBitArray(baAnd);

            // Perform OR operation and output the result
            BitArray baOr = new BitArray(ba1); // Copy the original ba1 again.
            baOr.Or(ba2); // 60 | 13 = 61
            Console.WriteLine("Bit array after OR operation (61):");
            PrintBitArray(baOr);

            // Perform XOR operation and output the result
            BitArray baXor = new BitArray(ba1); // Continue copying the original ba1.
            baXor.Xor(ba2); // 60 ^ 13 = 49
            Console.WriteLine("Bit array after XOR operation (49):");
            PrintBitArray(baXor);

            Console.ReadKey();
        }

        // Reverse traversal so that the output conforms to the "most significant digit first" convention
        static void PrintBitArray(BitArray bitArray)
        {
            for (int i = bitArray.Length - 1; i >= 0; i--)
            {
                Console.Write($"{(bitArray[i] ? 1 : 0)} ");
            }
            Console.WriteLine("\n");
        }
    }
}

When the above code is compiled and executed, it produces the following results:

Bit array ba1 (60):
0 0 1 1 1 1 0 0

Bit array ba2 (13):
0 0 0 0 1 1 0 1

Bit array after AND operation (12):
0 0 0 0 1 1 0 0

Bit array after OR operation (61):
0 0 1 1 1 1 0 1

Bit array after XOR operation (49):
0 0 1 1 0 0 0 1

C# collections

other extensions