title: How to convert between byte and bit arrays with Java?
body: <p>I have the following code trying to convert between byte and bit arrays, somehow it's not converting correctly, what is wrong and how to correct it ?</p>
  
  <pre><code>  String getBitsFromBytes(byte[] Byte_Array)                // 129
    {
      String Bits="";
  
      for (int i=0;i&lt;Byte_Array.length;i++) Bits+=String.format("%8s",Integer.toBinaryString(Byte_Array[i] &amp; 0xFF)).replace(' ','0');
      System.out.println(Bits);                               // 10000001
      return Bits;
    }
  
    byte[] getBytesFromBits(int[] bits)
    {
      byte[] results=new byte[(bits.length+7)/8];
      int byteValue=0;
      int index;
      for (index=0;index&lt;bits.length;index++)
      {
        byteValue=(byteValue&lt;&lt;1)|bits[index];
        if (index%8==7) results[index/8]=(byte)byteValue;
      }
  
      if (index%8!=0) results[index/8]=(byte)((byte)byteValue&lt;&lt;(8-(index%8)));
      System.out.println(Arrays.toString(results));
  
      return results;
    }
  
  ...
  
  String bit_string=getBitsFromBytes("ab".getBytes());                // 0110000101100010  :  01100001  +  01100010   --&gt;   ab
  
  int[] bits=new int[bit_string.length()];
  for (int i=0;i&lt;bits.length;i++) bits[i]=Integer.parseInt(bit_string.substring(i,i+1));
  getBytesFromBits(bits);
  </code></pre>
  
  <p>When I ran it, I got the following :</p>
  
  <pre><code>0110000101100010
  [97, 98]
  </code></pre>
  
  <p>I was expecting this :</p>
  
  <pre><code>0110000101100010
  [a, b]
  </code></pre>