BitArray.cs

/******************************************************************************
Module:  BitArray.cs
Notices: Copyright (c) 2002 Jeffrey Richter
******************************************************************************/


using System;


///////////////////////////////////////////////////////////////////////////////


public sealed class BitArray {
   // Private array of bytes that hold the bits
   private Byte[] byteArray;
   private Int32 numBits;

   // Constructor that allocates the byte array and sets all bits to 0
   public BitArray(Int32 numBits) {
      // Validate arguments first.
      if (numBits <= 0)
         throw new ArgumentOutOfRangeException("numBits must be > 0");

      // Save the number of bits.
      this.numBits = numBits;

      // Allocate the bytes for the bit array.
      byteArray = new Byte[(numBits + 7) / 8];
   }


   // This is the indexer.
   public Boolean this[Int32 bitPos] {
      // This is the index property抯 get accessor method.
      get {
         // Validate arguments first
         if ((bitPos < 0) || (bitPos >= numBits))
            throw new IndexOutOfRangeException();

         // Return the state of the indexed bit.
         return((byteArray[bitPos / 8] & (1 << (bitPos % 8))) != 0);
      }

      // This is the index property抯 set accessor method.
      set {
         if ((bitPos < 0) || (bitPos >= numBits))
            throw new IndexOutOfRangeException();
         if (value) {
            // Turn the indexed bit on.
            byteArray[bitPos / 8] = (Byte)
               (byteArray[bitPos / 8] | (1 << (bitPos % 8)));
         } else {
            // Turn the indexed bit off.
            byteArray[bitPos / 8] = (Byte)
               (byteArray[bitPos / 8] & ~(1 << (bitPos % 8)));
         }
      }
   }
}


///////////////////////////////////////////////////////////////////////////////


class App {
   static void Main() {
      // Allocate a BitArray that can hold 14 bits.
      BitArray ba = new BitArray(14);

      // Turn all the even-numbered bits on by calling the set accessor.
      for (Int32 x = 0; x < 14; x++) {
         ba[x] = (x % 2 == 0);
      }

      // Show the state of all the bits by calling the get accessor.
      for (Int32 x = 0; x < 14; x++) {
         Console.WriteLine("Bit " + x + " is " + (ba[x] ? "On" : "Off"));
      }
   }
}


//////////////////////////////// End of File //////////////////////////////////

你可能感兴趣的:(array)