CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Hybrid View

  1. #1
    Join Date
    Oct 2018
    Posts
    2

    [RESOLVED] how is bit shifting used in bitarray class

    I can not get my head around what is happening in the lines below with the << operator. I have put a comment under each line. This code is from BitArray class, and Jeff Richter uses it in his book C# via CLR. It is on page 244.
    Code:
    public sealed class BitArray {
      private Byte[] m_byteArray;
      private Int32 m_numBits;
    //constructor that allocates the byte array and sets all bits to zero
    public BitArray (Int32 numBits) {
    // validate arguments first
    if (numBits <= 0)
       throw new ArgumentOutOfRangeException("numBits must be > 0");
    // Save the number of bits. 
    m_numBits = numBits;
    // Allocate the bytes for the bit array.
    m_byteArray = new Byte[(numBits + 7) / 8];
    }
    // This is the indexer (parameterful property).
    public Boolean this[Int32 bitPos] {
    
    // This is the indexer's get accessor method
      get {
        // Validate arguments first
        if ((bitPos < 0) || (bitPos >= m_numBits))
           throw new ArgumentOutOfRangeException("bitPos");
        // Return the state of the indexed bit
        return (m_byteArray[bitPos / 8] & ( 1 << (bitPos % 8  ))) != 0;
    //What is happening in the above code? Why are we shifting 1s mod number of bitPos?
    }
    //This is the indexer's set accessor method.
    set {
      if ((bitPos < 0) || (bitPos >= m_numBits))
          throw new ArgumentOutOfRangeException("bitPos", bitPos.ToString());
      if (value) {
         // Turn the indexed bit on.
         m_byteArray[bitPos / 8] = (Byte)
            (m_byteArray[bitPos /8] | (1 << (bitPos % 8)));
      } else {
         // Turn the indexed bit off.
         m_byteArray[bitPos /8] = (Byte)
            (m_byteArray[bitPos / 8] & ~(1 << (bitPos % 8)));
    //In the above code the opposite is happening; there is a "~" next to the shif expression
      }
     }
    }
    }

  2. #2
    Join Date
    Oct 2018
    Posts
    2

    Re: [RESOLVED] how is bit shifting used in bitarray class

    I figured out what is going on. Bitarray indexer performs an and operation with what is the bitPos and 1.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured