StringCodec implements BlockCodec<String> { @Override public String decode(byte[] data, int bitLength) throws BlockCodecException { try { byte[] value = new byte[data.length]; for (int i = 0; i < data.length; i++) { value[i] = data[i] != this.empty ? data[i] : 0x20; } return new String(Arrays.copyOfRange(value, 0, bitLength / 8), this.encoding).trim(); } catch (Exception ex) { throw new BlockCodecException("string decode failure. " + ex.getMessage(), ex); } } StringCodec(); String getEmptyByte(); void setEmptyByte(String empty); String getEncoding(); void setEncoding(String encoding); @Override String zeroValue(); @Override String decode(byte[] data, int bitLength); @Override byte[] encode(String data, int bitLength); @Override void reset(); @Override String getValueType();  }
@Test public void testDecode() throws Exception { StringCodec codec = new StringCodec(); Assert.assertArrayEquals(new byte[] { (byte) 0xe8, (byte) 0xaa, (byte) 0xb0, 0x20 }, codec.encode("誰", 32)); codec.setEncoding("GBK"); Assert.assertArrayEquals(new byte[] { (byte) 0xb3, (byte) 0xc2, (byte) 0x20, 0x20 }, codec.encode("陈", 32)); codec.setEmptyByte("00"); Assert.assertArrayEquals(new byte[] { (byte) 0xb3, (byte) 0xc2, (byte) 0x00, 0x00 }, codec.encode("陈", 32)); }