C# - BitArray 类
BitArray 类管理一个紧凑的位值数组,这些位值以布尔值表示,其中 true 表示该位为开启状态 (1),false 表示该位为关闭状态 (0)。
当您需要存储位但事先不知道位数时,可以使用该类。您可以使用从零开始的整数索引来访问 BitArray 集合中的项目。
BitArray 类的方法和属性
下表列出了 BitArray 类的一些常用属性 -
| Sr.No. | 属性 &描述 |
|---|---|
| 1 | Count 获取 BitArray 中包含的元素数量。 |
| 2 | IsReadOnly 获取一个值,指示 BitArray 是否为只读。 |
| 3 | Item 获取或设置 BitArray 中特定位置的位值。 |
| 4 | Length 获取或设置 BitArray 中元素的数量BitArray。 |
下表列出了 BitArray 类的一些常用方法 -
| 序号 | 方法 &说明 |
|---|---|
| 1 | public BitArray And(BitArray value); 对当前 BitArray 中的元素与指定 BitArray 中的相应元素执行按位与运算。 |
| 2 | public bool Get(int index); 获取 BitArray 中特定位置的位值。 |
| 3 | public BitArray Not(); 反转当前 BitArray 中的所有位值,将设置为 true 的元素更改为 false,将设置为 false 的元素更改为true。 |
| 4 | public BitArray Or(BitArray value); 对当前 BitArray 中的元素与指定 BitArray 中的相应元素执行按位或运算。 |
| 5 | public void Set(int index, bool value); 将 BitArray 中特定位置的位设置为指定值。 |
| 6 | public void SetAll(bool value); 将 BitArray 中的所有位设置为指定值。 |
| 7 | public BitArray Xor(BitArray value); 对当前 BitArray 中的元素与指定 BitArray 中的相应元素执行按位异或运算。 |
示例
以下示例演示了 BitArray 类的用法 -
using System;
using System.Collections;
namespace CollectionsApplication {
class Program {
static void Main(string[] args) {
//创建两个大小为 8 的位数组
BitArray ba1 = new BitArray(8);
BitArray ba2 = new BitArray(8);
byte[] a = { 60 };
byte[] b = { 13 };
//将值 60 和 13 存储到位数组中
ba1 = new BitArray(a);
ba2 = new BitArray(b);
//ba1的内容
Console.WriteLine("Bit array ba1: 60");
for (int i = 0; i < ba1.Count; i++) {
Console.Write("{0, -6} ", ba1[i]);
}
Console.WriteLine();
//ba2的内容
Console.WriteLine("Bit array ba2: 13");
for (int i = 0; i < ba2.Count; i++) {
Console.Write("{0, -6} ", ba2[i]);
}
Console.WriteLine();
BitArray ba3 = new BitArray(8);
ba3 = ba1.And(ba2);
//ba3的内容
Console.WriteLine("Bit array ba3 after AND operation: 12");
for (int i = 0; i < ba3.Count; i++) {
Console.Write("{0, -6} ", ba3[i]);
}
Console.WriteLine();
ba3 = ba1.Or(ba2);
//ba3的内容
Console.WriteLine("Bit array ba3 after OR operation: 61");
for (int i = 0; i < ba3.Count; i++) {
Console.Write("{0, -6} ", ba3[i]);
}
Console.WriteLine();
Console.ReadKey();
}
}
}
当编译并执行上述代码时,它会产生以下结果 -
Bit array ba1: 60 False False True True True True False False Bit array ba2: 13 True False True True False False False False Bit array ba3 after AND operation: 12 False False True True False False False False Bit array ba3 after OR operation: 61 True False True True False False False False

csharp_collections.html