4.9 Working with BitArrays

 <  Day Day Up  >  

4.9 Working with BitArray s

You want to create an array of Boolean values and manipulate them using Boolean logic.


Technique

Create a BitArray object using one of its six constructors. By passing a single integer value into the constructor, you can create a BitArray with a bit count equal to that integer. By default, these bits are initialized to false . You might also pass an additional Boolean value if you want to override the default bit initialization:

 
 BitArray bt = new BitArray( 32, true ); 

You can also pass an array of values into the constructor. The size of the BitArray is equal to the number of items within the array passed into the constructor multiplied by the size of that array's data type. An integer array therefore would add 32 bits to the bit array for each integer in the integer array. Furthermore, the bits in the BitArray are initialized based on the bits of the values passed in the array via the constructor:

 
 int[] intArray = {1,2,3,4,5}; BitArray bt = new BitArray( intArray ); 

Comments

BitArray s are useful when you need to store a larger number of Boolean values to designate certain states and configuration parameters in your object. One of the more common uses of bits to store this information is objects that use flags to control their behavior. A BitArray behaves similarly to a single-dimension array, but rather than store integers or other data types, which consequently would consume more memory than is needed, the BitArray creates an array of Boolean values. You can then access these values as you do any other array through the use of an indexer. Each index value corresponds to a certain bit or Boolean value in the BitArray . Listing 4.3 shows how you can use a BitArray to create flags within your class. In this example, the Coffee class contains a private BitArray corresponding to the possible ingredients you can add to a cup of coffee. A user using the class can then add ingredients using a value from the defined enumerated type. The value of that ingredient is then used as the index into the BitArray , and the corresponding bit is set to true , as shown in the AddIngredient method. Imagine what it would be like if you didn't use this method. You would have to create either a property for each ingredient or a method that performed a lengthy switch of if / then / else statements. BitArray s allow you to save some of the hassles associated with simple Boolean configuration values.

Listing 4.3 Representing Configuration Flags Within Your Class
 using System; using System.Collections; namespace _8_BitArrays {     enum Ingredients     {         ice, sugar, cream, chocolate, milk, syrup, cinnamon, decaf     }     class Coffee     {         private BitArray ingredientFlags;         public Coffee()         {             ingredientFlags = new BitArray(8);         }         public void AddIngredient(Ingredients Ingredient)         {             ingredientFlags[(int) Ingredient] = true;         }     }     public void ListIngredients()     {         Console.WriteLine( "Coffee Ingredients\n------------------");         for( int i = 0; i < ingredientFlags.Count; i++ )         {             if( ingredientFlags[i] )             {                 Console.WriteLine( "-" +                     Enum.GetName(typeof(Ingredients), i) );             }         }     }     class Class1     {         [STAThread]         static void Main(string[] args)         {              Coffee latte = new Coffee();              latte.AddIngredient( Ingredients.sugar );              latte.AddIngredient( Ingredients.cream );              latte.AddIngredient( Ingredients.decaf );              latte.ListIngredients();         }     } } 

As you saw earlier, the BitArray class contains several useful constructors that allow you to create bit arrays of different sizes as well as control how the individual bits are initialized. The simplest way is to pass a single integer into the constructor and a Boolean value specifying what each bit should be initialized to. Traditional methods of using bit arrays or bit fields required you to use, for instance, an integer. They would give you 32 bits to work with even though you might only use a fraction of them. A BitArray , on the other hand, lets you create as many or as few bits as needed. Although on the outside it might seem that you are saving memory, don't forget that the BitArray is a .NET Framework class derived from System.Object and as such consumes more memory than a single integer because it is a class and not a value. However, the ability to create only a few bit fields instead of a greater amount of unused fields might seem like a good tradeoff .

A few of the constructors of the BitArray class allow you to pass in an array of values, such as an array of integers, bytes, or Booleans, which each correspond to 32 bits, 8 bits, and 1 bit, respectively. The behavior of passing in an array instead of a single integer changes the behavior of the BitArray object creation. For each value in the array passed in, the BitArray creates a number of bits equal to the size of the data type passed in. If you pass in an integer array with five values, 32 bits are created for each of those five values, giving a total of 160 bits. Those bits are then initialized based on the actual values of the passed-in array. The first 32 bits are set to the value of the bits in the first value of the integer array; the second 32 bits are initialized to the same value as the bits of the second value of the integer array; and so on. Passing an array of values into the constructor of a BitArray not only allows you to specify how many bits to create (in multiples of the array data type size) but also allows you to initialize the individual bits in one method call.

The BitArray class also contains methods that allow you to manipulate the internal bits using Boolean logic. Due to the fact that the BitArray can contain any number of bits, you are limited to either performing Boolean logic on a single bit or passing in a different BitArray . In other words, you cannot perform a Boolean logic operation using a value such as an integer or byte because you cannot guarantee the BitArray contains the same number of bits of that data type. The available logic operations are and , or , xor , and not in addition to the regular Boolean logic operators that work with a single bit. The following code shows how you can easily clear or set each bit to 0 by using the Xor method. Xor will set a bit to true if either bit is set to true but not both. Therefore, if you xor a set of bits with itself, it sets all of the bits to false or . Take note, however, that the BitArray class also contains a SetAll method, which can also set all the bits to false .

 
 public void Drink() {         ingredientFlags.Xor( ingredientFlags );         Console.WriteLine( "\nDrank Coffee" );         ListIngredients(); } 
 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net