public int readBits(int count) throws IOException {

        if (count <= 32) {
            // catch-all
            int result = 0;
            // int done = 0;

            if (cacheBitsRemaining > 0) {
                if (count >= cacheBitsRemaining) {
                    result = (1 << cacheBitsRemaining) - 1 & cache;
                    count -= cacheBitsRemaining;
                    cacheBitsRemaining = 0;
                } else {
                    // cache >>= count;
                    cacheBitsRemaining -= count;
                    result = (1 << count) - 1 & cache >> cacheBitsRemaining;
                    count = 0;
                }
            }
            while (count >= 8) {
                cache = in.read();
                if (cache < 0) {
                    throw new ImagingException("Couldn't read bits");
                }
                // System.out.println("cache 1: " + cache + " ("
                // + Integer.toHexString(cache) + ", "
                // + Integer.toBinaryString(cache) + ")");
                bytesRead++;
                result = result << 8 | 0xff & cache;
                count -= 8;
            }
            if (count > 0) {
                cache = in.read();
                if (cache < 0) {
                    throw new ImagingException("Couldn't read bits");
                }
                // System.out.println("cache 2: " + cache + " ("
                // + Integer.toHexString(cache) + ", "
                // + Integer.toBinaryString(cache) + ")");
                bytesRead++;
                cacheBitsRemaining = 8 - count;
                result = result << count | (1 << count) - 1 & cache >> cacheBitsRemaining;
                count = 0;
            }

            return result;
        }

        throw new ImagingException("BitInputStream: unknown error");

    }
Input stream that allows reading up to 32 bits across byte boundaries in most significant bit first order.
src/main/java/org/apache/commons/imaging/formats/tiff/itu_t4/BitInputStreamFlexible.java