Visual Basic 位数组(BitArray)
BitArray 类是一个紧凑的位值数组,表示为布尔值,其中 true 表示该位为 on(1),false 表示该位为 off(0)。
当您需要存储位,但却不知道位的数量时,可以使用该集合。您可以使用从 0 开始的 整数索引 访问 BitArray 集合中的项。
BitArray 类的属性和方法
下表列出了 BitArray 类的一些常用属性:
| 编号 | 属性 & 描述 |
|---|---|
| 1 | Count 获取 BitArray 中包含的元素数。 |
| 2 | IsReadOnly 获取一个值,该值表示 BitArray 是否为只读。 |
| 3 | Item 获取或设置 BitArray 中特定位置的位值。 |
| 4 | Length 获取或设置 BitArray 中的元素数。 |
下表列出了 BitArray 类的一些常用方法:
| 编号 | 方法名 & 用途 |
|---|---|
| 1 | Public Function And (value As BitArray) As BitArray 对当前位数组中的元素对指定位数组中的相应元素执行 按位与 运算。 |
| 2 | Public Function Get (index As Integer) As Boolean 获取位数组中特定位置的位的值。 |
| 3 | Public Function Not As BitArray 反转当前位数组中的所有位值,以便将设置为 true 的元素更改为 false,将设置为 false 的元素更改为 true。 |
| 4 | Public Function Or (value As BitArray) As BitArray 对当前位数组中的元素对指定位数组中的相应元素执行 按位或 运算。 |
| 5 | Public Sub Set (index As Integer, value As Boolean ) 将位数组中特定位置的位设置为指定值。 |
| 6 | Public Sub SetAll (value As Boolean) 将位数组中的所有位设置为指定值。 |
| 7 | Public Function Xor (value As BitArray) As BitArray 对当前位数组中的元素对指定位数组中的相应元素执行 按位异或 操作。 |
实例
Module collectionsSub Main()'creating two bit arrays of size 8Dim ba1 As BitArray = New BitArray(8)Dim ba2 As BitArray = New BitArray(8)Dim a() As Byte = {60}Dim b() As Byte = {13}'storing the values 60, and 13 into the bit arraysba1 = New BitArray(a)ba2 = New BitArray(b)'content of ba1Console.WriteLine("Bit array ba1: 60")Dim i As IntegerFor i = 0 To ba1.CountConsole.Write("{0 } ", ba1(i))Next iConsole.WriteLine()'content of ba2Console.WriteLine("Bit array ba2: 13")For i = 0 To ba2.CountConsole.Write("{0 } ", ba2(i))Next iConsole.WriteLine()Dim ba3 As BitArray = New BitArray(8)ba3 = ba1.And(ba2)'content of ba3Console.WriteLine("Bit array ba3 after AND operation: 12")For i = 0 To ba3.CountConsole.Write("{0 } ", ba3(i))Next iConsole.WriteLine()ba3 = ba1.Or(ba2)'content of ba3Console.WriteLine("Bit array ba3 after OR operation: 61")For i = 0 To ba3.CountConsole.Write("{0 } ", ba3(i))Next iConsole.WriteLine()Console.ReadKey()End SubEnd Module
结果如下:
Initial valuesmyBA1: False False True TruemyBA2: False True False TrueResultXOR: False True True FalseAfter XORmyBA1: False True True FalsemyBA2: False True False True