public static ImmutableByteSequence copyAndFit(ByteBuffer original, int bitWidth)
            throws ByteSequenceTrimException {
        checkArgument(original != null && original.capacity() > 0,
                      "Cannot copy from an empty or null byte buffer");
        checkArgument(bitWidth > 0,
                      "bit-width must be a non-zero positive integer");
        if (original.order() == ByteOrder.LITTLE_ENDIAN) {
            // FIXME: this can be improved, e.g. read bytes in reverse order from original
            byte[] newBytes = new byte[original.capacity()];
            original.get(newBytes);
            reverse(newBytes);
            return internalCopyAndFit(ByteBuffer.wrap(newBytes), bitWidth);
        } else {
            return internalCopyAndFit(original.duplicate(), bitWidth);
        }
    }
@Test
    public void testCopyAndFit() throws Exception {
        int originalByteWidth = 3;
        int paddedByteWidth = 4;
        int trimmedByteWidth = 2;
        int indexFirstNonZeroByte = 1;

        byte byteValue = (byte) 1;
        byte[] arrayValue = new byte[originalByteWidth];
        arrayValue[indexFirstNonZeroByte] = byteValue;
        ByteBuffer bufferValue = ByteBuffer.allocate(originalByteWidth).put(arrayValue);

        ImmutableByteSequence bsBuffer = ImmutableByteSequence.copyAndFit(
                bufferValue, originalByteWidth * 8);
        ImmutableByteSequence bsBufferTrimmed = ImmutableByteSequence.copyAndFit(
                bufferValue, trimmedByteWidth * 8);
        ImmutableByteSequence bsBufferPadded = ImmutableByteSequence.copyAndFit(
                bufferValue, paddedByteWidth * 8);

        assertThat("byte sequence of the byte buffer must be 3 bytes long",
                   bsBuffer.size(), is(equalTo(originalByteWidth)));
        assertThat("byte sequence of the byte buffer must be 3 bytes long",
                   bsBufferTrimmed.size(), is(equalTo(trimmedByteWidth)));
        assertThat("byte sequence of the byte buffer must be 3 bytes long",
                   bsBufferPadded.size(), is(equalTo(paddedByteWidth)));

        String errStr = "incorrect byte sequence value";

        assertThat(errStr, bsBuffer.asArray()[indexFirstNonZeroByte], is(equalTo(byteValue)));
        assertThat(errStr, bsBufferTrimmed.asArray()[indexFirstNonZeroByte - 1], is(equalTo(byteValue)));
        assertThat(errStr, bsBufferPadded.asArray()[indexFirstNonZeroByte + 1], is(equalTo(byteValue)));
        assertThat(errStr, bsBufferPadded.asArray()[paddedByteWidth - 1], is(equalTo((byte) 0x00)));
    }