Pixel bit-wise LSB extraction to byte array
I believe your basic algorithm is fine. Shifting only 4 bits on to each byte is not exactly filling the byte, but, there are ways I would consider neatening up the process. Note that this does not change the algorithm much at all.

Here are some tricks to note, though...


You should pass in the number of bits you want in a byte as a parameter value, or it should be a constant. The value 4 is a magic number that should not be there in the method.

private static final int BITS_IN_BYTE = 4;

You have: int numberOfBytes = (int) Math.ceil(pixelCount / 4.0);. This can be done "better" with:

int numberOfBytes = (pixelCount + BITS_IN_BYTE - 1) / BITS_IN_BYTE;

You declare convenience variables which really are unnecessary....
You are working with the data 'backwards'.... you build up the byte, then set the value in to the output, instead of just shifting the bits in to the output.


Here's how I would have written your code. It is more concise, but essentially the same.

public static byte[] extractLSBRL(final int perByte, final int[] pixels) {
    final int outSize = (pixels.length + perByte - 1) / perByte;
    final byte[] lsbs = new byte[outSize];
    for (int i = 0; i &lt; pixels.length; i++) {
        // which output byte is the one for this pixel
        final int j = i / perByte;
        // make space for the new bit to arrive.
        lsbs[j] &lt;&lt;= 1;
        // copy the bit in to the output byte's position.
        lsbs[j] |= pixels[i] &amp; 1;
    }
    return lsbs;

}


Note that I have a concern about the output here. are you sure the last byte should be 10, and not 1000 (i.e. shifted two bits to the left?). Just checking... different algorithms expect different things....