IntegerLSBCodec implements BlockCodec<Integer> { @Override public byte[] encode(Integer data, int bitLength) throws BlockCodecException { int value = data.intValue(); if (this.unsigned && value < 0) { throw new BlockCodecException("integer(LSB,unsigned) encode failure. value(" + value + ") is less than zero."); } try { byte[] temp = this.unsigned ? new byte[] { (byte) value, (byte) (value >>> 8), (byte) (value >>> 16), (byte) (value >>> 24) } : new byte[] { (byte) value, (byte) (value >> 8), (byte) (value >> 16), (byte) (value >> 24) }; int byteStart = bitLength / 8; int bitStart = bitLength % 8; if (bitStart != 0) { bitStart = 8 - bitStart; } if (byteStart < 4) { temp[byteStart] = (byte) (temp[byteStart] << bitStart); } return ByteUtils.copyBits(temp, 0, bitLength); } catch (Exception ex) { throw new BlockCodecException("integer(LSB) encode failure. " + ex.getMessage(), ex); } } IntegerLSBCodec();  IntegerLSBCodec(boolean unsigned); void setUnsigned(String yn); String getUnsigned(); @Override Integer zeroValue(); @Override Integer decode(byte[] data, int bitLength); @Override byte[] encode(Integer data, int bitLength); @Override void reset(); @Override String getValueType();  }
@Test public void testEncode() throws Exception { IntegerLSBCodec codec = new IntegerLSBCodec(); Assert.assertArrayEquals(new byte[] { (byte) 0xfe }, codec.encode(-1, 7)); Assert.assertArrayEquals(new byte[] { (byte) 0xfe, (byte) 0xff }, codec.encode(-2, 16)); Assert.assertArrayEquals(new byte[] { (byte) 0x01, (byte) 0xc0 }, codec.encode(-255, 10)); Assert.assertArrayEquals(new byte[] { (byte) 0xfc, (byte) 0xff, (byte) 0xff }, codec.encode(-4, 24)); codec.reset(); }