15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Bit arrays ❘ 259<br />

The example to demonstrate the BitArray class creates a bit array with 8 bits, indexed from 0 to 7. The<br />

SetAll() method sets all 8 bits to true. Then the Set() method changes bit 1 to false. Instead of the Set<br />

method, you can also use an indexer, as shown with index 5 <strong>and</strong> 7:<br />

var bits1 = new BitArray(8);<br />

bits1.SetAll(true);<br />

bits1.Set(1, false);<br />

bits1[5] = false;<br />

bits1[7] = false;<br />

Console.Write("initialized: ");<br />

DisplayBits(bits1);<br />

Console.WriteLine();<br />

This is the displayed result of the initialized bits:<br />

initialized: 10111010<br />

The Not() method generates the inverse of the bits of the BitArray:<br />

Console.Write(" not ");<br />

DisplayBits(bits1);<br />

bits1.Not();<br />

Console.Write(" = ");<br />

DisplayBits(bits1);<br />

Console.WriteLine();<br />

The result of Not() is all bits inversed. If the bit was true, it is false, <strong>and</strong> if it was false, it is true:<br />

not 10111010 = 01000101<br />

Here, a new BitArray is created. With the constructor, the variable bits1 is used to initialize the array, so<br />

the new array has the same values. Then the values for bits 0, 1, <strong>and</strong> 4 are set to different values. Before<br />

the Or() method is used, the bit arrays bits1 <strong>and</strong> bits2 are displayed. The Or() method changes the values<br />

of bits1:<br />

var bits2 = new BitArray(bits1);<br />

bits2[0] = true;<br />

bits2[1] = false;<br />

bits2[4] = true;<br />

DisplayBits(bits1);<br />

Console.Write(" or ");<br />

DisplayBits(bits2);<br />

Console.Write(" = ");<br />

bits1.Or(bits2);<br />

DisplayBits(bits1);<br />

Console.WriteLine();<br />

With the Or() method, the set bits are taken from both input arrays. In the result, the bit is set if it was set<br />

with either the first or the second array:<br />

01000101 or 10001101 = 11001101<br />

Next, the And() method is used to operate on bits2 <strong>and</strong> bits1:<br />

DisplayBits(bits2);<br />

Console.Write(" <strong>and</strong> ");<br />

DisplayBits(bits1);<br />

Console.Write(" = ");<br />

bits2.And(bits1);<br />

DisplayBits(bits2);<br />

Console.WriteLine();<br />

The result of the And() method only sets the bits where the bit was set in both input arrays:<br />

10001101 <strong>and</strong> 11001101 = 10001101<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!