Area di riferimento
- Developing applications that use system types and collections
- Manage a group of associated data in a .NET Framework application by using collections. (Refer System.Collections namespace)
- BitArray class
BitArray class
La classe BitArray è un collection ridimensionabile in grado di memorizzare valori booleani e consente di eseguire semplice operazioni logiche.
Ecco un esempio di utilizzo:
static void Main()
{
BitArray a = new BitArray(3); // creo un array di bit lungo 3
a[0] = true;
a[1] = true;
a[2] = true;
BitArray b = new BitArray(3);
b[0] = false;
b[1] = false;
b[2] = true;
// Creo i vettori di bit che conterranno i risultati
BitArray and = new BitArray(a);
BitArray or = new BitArray(a);
BitArray xor = new BitArray(a);
BitArray not = new BitArray(a);
// Operazioni tra vettori di bit
and.And(b);
or.Or(b);
xor.Xor(b);
not.Not();
// Stampa dei risultati
Console.WriteLine("a = {0}", getBits(a)); // a = 111
Console.WriteLine("b = {0}", getBits(b)); // b = 001
Console.WriteLine("a and b = {0}", getBits(and)); // a and b = 001
Console.WriteLine("a or b = {0}", getBits(or)); // a or b = 111
Console.WriteLine("a xor b = {0}", getBits(xor)); // a xor b = 110
Console.WriteLine(" not a = {0}", getBits(not)); // not a = 000
Console.ReadKey();
}
// Funzione che stampa l'array di bit
static string getBits(BitArray b)
{
StringBuilder sb = new StringBuilder(b.Length);
foreach (bool bit in b)
{
sb.Append( bit == true ? '1' : '0' );
}
return sb.ToString();
}