ByteArrayCodec implements BlockCodec<byte[]> { @Override public byte[] encode(byte[] data, int bitLength) throws BlockCodecException { if (bitLength < 0) { return data; } byte[] result = Arrays.copyOf(data, (int) Math.ceil((double) bitLength / 8)); int off = bitLength % 8; if (off != 0) { byte zero = (byte) (0xff << (8 - off)); result[result.length - 1] &= zero; } return result; }  @Override byte[] zeroValue(); @Override byte[] decode(byte[] data, int bitLength); @Override byte[] encode(byte[] data, int bitLength); @Override void reset(); @Override String getValueType();  }
@Test public void testEncode() throws Exception { ByteArrayCodec codec = new ByteArrayCodec(); Assert.assertArrayEquals(new byte[] { 0x60 }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 3)); Assert.assertArrayEquals(new byte[] { 0x70 }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 4)); Assert.assertArrayEquals(new byte[] { 0x78 }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 5)); Assert.assertArrayEquals(new byte[] { 0x7c }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 6)); Assert.assertArrayEquals(new byte[] { 0x7e }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 7)); Assert.assertArrayEquals(new byte[] { 0x7f }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 8)); Assert.assertArrayEquals(new byte[] { (byte) 0x7f, (byte) 0x80 }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 9)); Assert.assertArrayEquals(new byte[] { (byte) 0x7f, (byte) 0xc0 }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 10)); Assert.assertArrayEquals(new byte[] { (byte) 0x7f, (byte) 0xe0 }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 11)); Assert.assertArrayEquals(new byte[] { (byte) 0x7f, (byte) 0xf0 }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 12)); Assert.assertArrayEquals(new byte[] { (byte) 0x7f, (byte) 0xf0 }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 13)); Assert.assertArrayEquals(new byte[] { (byte) 0x7f, (byte) 0xf0 }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 14)); Assert.assertArrayEquals(new byte[] { (byte) 0x7f, (byte) 0xf2 }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 15)); Assert.assertArrayEquals(new byte[] { (byte) 0x7f, (byte) 0xf3 }, codec.encode(new byte[] { (byte) 0x7f, (byte) 0xf3 }, 16)); }