class CompactEncoder {

    public static byte[] packNibbles(byte[] nibbles) {
        int terminator = 0;

        if (nibbles[nibbles.length - 1] == TERMINATOR) {
            terminator = 1;
            nibbles = copyOf(nibbles, nibbles.length - 1);
        }
        int oddlen = nibbles.length % 2;
        int flag = 2 * terminator + oddlen;
        if (oddlen != 0) {
            byte[] flags = new byte[]{(byte) flag};
            nibbles = concatenate(flags, nibbles);
        } else {
            byte[] flags = new byte[]{(byte) flag, 0};
            nibbles = concatenate(flags, nibbles);
        }
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        for (int i = 0; i < nibbles.length; i += 2) {
            buffer.write(16 * nibbles[i] + nibbles[i + 1]);
        }
        return buffer.toByteArray();
    }

}