15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

258 ❘ ChaPTer 10 cOllectiOns<br />

starting index for new item(s): 1<br />

new item(s):<br />

Three<br />

action: Remove<br />

starting index for old item(s): 0<br />

old item(s):<br />

One<br />

biT arrays<br />

If you need to deal with a number of bits, you can use the class BitArray <strong>and</strong> the struct BitVector32.<br />

BitArray is located in the namespace System.Collections; BitVector32 is in the namespace System.<br />

Collections.Specialized. The most important difference between these two types is that BitArray is<br />

resizable, which is useful if you don’t know the number of bits needed in advance, <strong>and</strong> it can contain a large<br />

number of bits. BitVector32 is stack-based <strong>and</strong> therefore faster. BitVector32 contains only 32 bits, which<br />

are stored in an integer.<br />

bitarray<br />

The class BitArray is a reference type that contains an array of ints, where for every 32 bits a new integer<br />

is used. Members of this class are explained in the following table:<br />

biTarray members<br />

Count Length<br />

Item Get() Set()<br />

SetAll()<br />

Not()<br />

And() Or() Xor()<br />

desCriPTion<br />

The get accessor of both Count <strong>and</strong> Length return the number of bits in the<br />

array. With the Length property, you can also define a new size <strong>and</strong> resize the<br />

collection.<br />

You can use an indexer to read <strong>and</strong> write bits in the array. The indexer is of type bool.<br />

Instead of using the indexer, you can also use the Get() <strong>and</strong> Set() methods to<br />

access the bits in the array.<br />

The method SetAll() sets the values of all bits according to the parameter passed<br />

to the method.<br />

The method Not() generates the inverse of all bits of the array.<br />

With the methods And(), Or(), <strong>and</strong> Xor(), you can combine two BitArray objects.<br />

The And() method does a binary AND, where the result bits are set only if the bits<br />

from both input arrays are set. The Or() method does a binary OR, where the result<br />

bits are set if one or both of the input arrays are set. The Xor() method is an exclusive<br />

OR, where the result is set if only one of the input bits is set.<br />

The helper method DisplayBits() iterates through a BitArray <strong>and</strong> displays 1 or 0 to the console, depending<br />

on whether or not the bit is set:<br />

static void DisplayBits(BitArray bits)<br />

{<br />

foreach (bool bit in bits)<br />

{<br />

Console.Write(bit 1: 0);<br />

}<br />

}<br />

code snippet BitArraySample/Program.cs<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!