title: Bitwise operators on different length BitArrays
body: <p>I have 2 BitArray items and I need to know if any of bits are the same in each, "AND".
  However, the length of the BitArrays can be different and ether one can be larger or smaller than the other.</p>
  
  <p>How can I do an "AND" of two BitArrays, without getting an exception because of different sizes?
  This is going to happen a lot, so I need it to be fairly quick.</p>
  
  <p>Example</p>
  
  <pre><code>  int[] ids = new int[3];
    ids[0] = 1;
    ids[1] = 3;
    ids[2] = 5;
    BitArray bs1 = new BitArray(ids.Max()+1);
    for (int i = 0; i &lt; ids.Count(); ++i)
    {
      bs1[ids[i]] = true;
    }
  
  
    ids[0] = 1;
    ids[1] = 59;
    ids[2] = 1111;
    BitArray bs2 = new BitArray(ids.Max()+1);
    for (int i = 0; i &lt; ids.Count(); ++i)
    {
      bs2[ids[i]] = true;
    }
  
    ids[0] = 0;
    ids[1] = 5;
    ids[2] = 33;
    BitArray bs3 = new BitArray(ids.Max()+1);
    for (int i = 0; i &lt; ids.Count(); ++i)
    {
      bs3[ids[i]] = true;
    }
  
  
    //if bs1 AND bs2 bitcount &gt; 0 DisplayMessage("1 and 2 has some same items")
    //if bs1 AND bs3 bitcount &gt; 0 DisplayMessage("1 and 3 has some same items")
    //if bs2 AND bs3 bitcount &gt; 0 DisplayMessage("2 and 3 has some same items")
  </code></pre>
  
  <p>To solve my problem I modified the BitArray code and added the following</p>
  
  <pre><code>public static MyBitArray TruncateCopy(MyBitArray source, int size)
  {
    MyBitArray dest = new MyBitArray(size);
  
    //copy all the arrays
    for (int i = 0; i &lt; dest.m_array.Length; ++i)
    {
      dest.m_array[i] = source.m_array[i];
    }
  
    //remove any of the items over the given size
    for (int i = ((size % 32) + 1); i &lt; 32; ++i)
    {
      dest.m_array[i &gt;&gt; 5] &amp;= ~(1 &lt;&lt; (i &amp; 31));
    }
  
    return dest;
  }
  
  public bool HasCommonBits(MyBitArray comp)
  {
    MyBitArray copied, other;
  
    if (this.Length &lt; comp.Length)
    {
      other = this;
      copied = TruncateCopy(comp, this.Length);
    }
    else
    {
      copied = TruncateCopy(this, comp.Length);
      other = comp;
    }
  
    MyBitArray compareEq = copied.And(other);
  
    return (!compareEq.IsEmpty());
  }
  
  public bool IsEmpty()
  {
    for (int i = 0; i &lt; this.m_array.Length; ++i)
    {
      if (m_array[i] != 0)
        return false;
    }
  
    return true;
  }
  
  public bool IsFull()
  {
    //run through all the full sets
    for (int i = 0; i &lt; this.m_array.Length - 1; ++i)
    {
      if (m_array[i] != -1) //-1 is all bits set in an integer
        return false;
    }
  
    //go through the partial one
    for (int i = 0; i &lt; (this.Length % 32); ++i)
    {
      if (!this[i])
        return false;
    }
  
    return true;
  }
  </code></pre>
  
  <p>}</p>