IntegerCodec 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(unsigned) encode failure. value(" + value + ") is less than zero."); } try { byte[] temp = new byte[] { (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value }; int byteStart = 4 - (int) Math.ceil((double) bitLength / 8); int bitStart = bitLength % 8; if (bitStart != 0) { bitStart = 8 - bitStart; } return ByteUtils.copyBits(temp, byteStart, bitStart, bitLength); } catch (Exception ex) { throw new BlockCodecException("integer encode failure. " + ex.getMessage(), ex); } } IntegerCodec();  IntegerCodec(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 { IntegerCodec codec = new IntegerCodec(); Assert.assertArrayEquals(new byte[] { (byte) 0x7f }, codec.encode(127, 8)); Assert.assertArrayEquals(new byte[] { (byte) 0xfe }, codec.encode(127, 7)); Assert.assertArrayEquals(new byte[] { 0x00, (byte) 0x7f }, codec.encode(127, 16)); Assert.assertArrayEquals(new byte[] { (byte) 0x80 }, codec.encode(-128, 8)); Assert.assertArrayEquals(new byte[] { (byte) 0xff, (byte) 0x00 }, codec.encode(-128, 15)); Assert.assertArrayEquals(new byte[] { (byte) 0xff, (byte) 0x80 }, codec.encode(-128, 16)); }