Convert byte[] to BitSet
<p>I'm trying to convert a byte array to a BitSet. The following is the code I'm using:</p>

<pre><code>public BitSet byteToBits(byte[] bytearray){
    BitSet returnValue = new BitSet(bytearray.length*8);
    ByteBuffer  byteBuffer = ByteBuffer.wrap(bytearray);
    //System.out.println(byteBuffer.asIntBuffer().get(1));
    //Hexadecimal values used are Big-Endian, because Java is Big-Endian
    for (int i = 0; i &lt; bytearray.length; i++) {
        byte thebyte = byteBuffer.get(i);
        for (int j = 0; j &lt;8 ; j++) {
            returnValue.set(i*8+j,isBitSet(thebyte,j));
        }
    }
    return returnValue;
}

private static Boolean isBitSet(byte b, int bit)
{
    return (b &amp; (1 &lt;&lt; bit)) != 0;
}
</code></pre>

<p>I'm testing it with a JUnit test, shown below.</p>

<pre><code>@org.junit.Test
public void byteToBits() throws Exception {
    byte[] input = new byte[]{(byte) 0b1011_1011};
    BitSet expectedOutput = new BitSet(8);
    expectedOutput = BitSet.valueOf(new byte[]{(byte)0b1011_1011});
    assertEquals(expectedOutput,converter.byteToBits(input));
    assertEquals(expectedOutput.toByteArray(),input);
}

@Test
public void testBytestoBitslength() throws Exception {
    byte[] input = new byte[]{(byte) 0xFFFF,(byte)0x7F70,(byte)0xF45A,(byte)0xA24B};
    BitSet output = converter.byteToBits(input);
    System.out.println("byte[] length: "+input.length+ "x8: "+input.length*8);
    System.out.println("BitSet length: "+output.length());
    System.out.println(input.toString());
    System.out.println(output.toByteArray().toString());
    assertTrue(output.length()==input.length*8);
}
</code></pre>

<p>This code fails the test though, and I have no idea why.</p>

<p>For byteToBits:</p>

<pre><code>java.lang.AssertionError: 
Expected :[B@6438a396
Actual   :[B@e2144e4
</code></pre>

<p>For testBytestoBitslength:</p>

<pre><code>byte[] length: 4x8: 32
BitSet length: 31
[B@4f2410ac
[B@722c41f4
</code></pre>

<p>Tried replacing it with a BitSet.valueOf(byte[]) method call. It still fails, albeit more interestingly.</p>

<pre><code>@Test
public void curiosity() throws Exception {
    byte[] byteArray = new byte[]{1, 2, 3};
    BitSet bitSet = BitSet.valueOf(byteArray);
    System.out.println("byte[]: "+byteArray);
    System.out.println(bitSet.toByteArray());
    assertEquals(ByteBuffer.wrap(byteArray),ByteBuffer.wrap(bitSet.toByteArray()));
    assertEquals(bitSet.length(),byteArray.length*8);
}
</code></pre>

<p>This returns the following:</p>

<pre><code>byte[]: [B@6438a396
BitSet: [B@e2144e4

java.lang.AssertionError: 
Expected :18
Actual   :24
</code></pre>

<p>When wrapped by a ByteBuffer, the two objects return the same thing, but they appear to be completely different, and the two objects have different lengths.</p>