class Convert {

    public static boolean getNthBit(byte[] arr, int offset){
        int arrayOffset = offset / 8;
        int bitOfByte = offset % 8;
        int maskedBit = arr[arrayOffset] & (1 << (7 - bitOfByte));
        return (maskedBit != 0);
    }

}

class ConvertTest {

    @Test
    public void testBitsBytesConvert() {


        Random r = new Random();

        boolean[] bits = new boolean[32];
        for (int i = 0; i < bits.length; i++) {
            bits[i] = r.nextBoolean();
        }

        // convert bits to byte array
        byte[] bytes = new byte[4];
        for (int i = 0;i < bits.length; i++) {
            if (bits[i]) {
                bytes[i/8] |= (1 << 7) >> (i%8);
            }
        }

        for (int i = 0; i < bits.length; i++) {
            if (Convert.getNthBit(bytes, i) != bits[i]) {
                fail("Conversion of bytes to bits failed at bit "+i);
            }
        }

    }

}