title: How can I convert bits to bytes?
body: <p>I have an array of 128 booleans that represent bits. How can I convert these 128 bit representations into 16 bytes?</p>
  
  <p>Example:</p>
  
  <p>I have an array that looks like this:</p>
  
  <pre><code>0110001100110000100010111011001011010011010001010001101101001100
  1000010000000000001000111111111101000011111001111011111011111001
  </code></pre>
  
  <p>(Converted to 1s and 0s to be more concise)</p>
  
  <p>I need to convert those bits to the following byte array:</p>
  
  <pre><code>99 48 139 178 211 69 27 76 132 0 35 255 67 231 190 249
  </code></pre>
  
  <p>EDIT: This doesn't seem to work:</p>
  
  <pre><code>public byte[] ToByteArray() {
      int numBytes = Count / 8;
  
      if (_bits.Count % 8 != 0) numBytes++;
  
      byte[] bytes = new byte[numBytes];
  
      int byteIndex = 0, bitIndex = 0;
  
      for (int i = 0; i &lt; _bits.Count; i++) {
          if (_bits[i])
              bytes[byteIndex] |= (byte)(1 &lt;&lt; bitIndex);
  
          bitIndex++;
          if (bitIndex == 8) {
              bitIndex = 0;
              byteIndex++;
          }
      }
  
      return bytes;
  }
  </code></pre>
  
  <p>It outputs:</p>
  
  <pre><code>198 12 209 77 203 162 216 50 33 0 196 255 194 231 125 159
  </code></pre>