zoukankan      html  css  js  c++  java
  • 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 //////////////////////////////////
  • 相关阅读:
    第三周作业
    第二周作业
    实时控制软件大作业总结
    实时控制软件大作业四
    实时控制软件大作业三
    实时控制软件大作业二
    轨迹插补程序
    实时控制软件大作业博客一
    实时控制软件设计第四周作业
    实时控制软件设计第三周作业-1
  • 原文地址:https://www.cnblogs.com/shihao/p/2501249.html
Copyright © 2011-2022 走看看