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(); }  static byte[] packNibbles(byte[] nibbles); static boolean hasTerminator(byte[] packedKey); static byte[] unpackToNibbles(byte[] str); static byte[] binToNibbles(byte[] str); static byte[] binToNibblesNoTerminator(byte[] str);  }
@Test public void testCompactEncodeOddCompact() { byte[] test = new byte[]{1, 2, 3, 4, 5}; byte[] expectedData = new byte[]{0x11, 0x23, 0x45}; assertArrayEquals("odd compact encode fail", expectedData, CompactEncoder.packNibbles(test)); }
@Test public void testCompactEncodeEvenCompact() { byte[] test = new byte[]{0, 1, 2, 3, 4, 5}; byte[] expectedData = new byte[]{0x00, 0x01, 0x23, 0x45}; assertArrayEquals("even compact encode fail", expectedData, CompactEncoder.packNibbles(test)); }
@Test public void testCompactEncodeEvenTerminated() { byte[] test = new byte[]{0, 15, 1, 12, 11, 8, T}; byte[] expectedData = new byte[]{0x20, 0x0f, 0x1c, (byte) 0xb8}; assertArrayEquals("even terminated compact encode fail", expectedData, CompactEncoder.packNibbles(test)); }
@Test public void testCompactEncodeOddTerminated() { byte[] test = new byte[]{15, 1, 12, 11, 8, T}; byte[] expectedData = new byte[]{0x3f, 0x1c, (byte) 0xb8}; assertArrayEquals("odd terminated compact encode fail", expectedData, CompactEncoder.packNibbles(test)); }