C# Bit array (BitArray)
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 Name | Type | Description |
|---|---|---|
Count | int | GetBitArrayThe number of bits contained (read-only). |
Length | int | Get or setBitArrayThe number of bits in (supports dynamic resizing). |
IsReadOnly | bool | Gets a value indicating whether theBitArrayis read-only (alwaysfalse)。 |
SyncRoot | object | Gets an object used to synchronize access to theBitArrayaccess. |
IsSynchronized | bool | Gets a value indicating whether access to theBitArrayis synchronized (thread-safe). |
Item[int index] | bool | Gets 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 Name | Return Type | Description |
|---|---|---|
And(BitArray) | BitArray | Bitwise 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) | BitArray | Bitwise 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) | BitArray | Bitwise XOR operation, on twoBitArrayperforms an XOR operation on the corresponding bits, modifies the current instance in place and returns the current instance itself. |
Not() | BitArray | Bitwise 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) | void | Sets the bit at the specified index to the specified value (trueorfalse)。 |
SetAll(bool value) | void | Sets all bits to the specified value (trueorfalse)。 |
Get(int index) | bool | Gets the value of the bit at the specified index. |
Clone() | object | Create currentBitArrayA shallow copy (duplicate) of. |
CopyTo(Array array, int index) | void | willBitArrayCopies the contents to the specified array, starting at the specified index. |
Equals(object obj) | bool | Determines whether the specified object is equal to the currentBitArray。 |
GetEnumerator() | IEnumerator | Returns 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.
Example
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
other extensions