Use the classes found in the java.nio
namespace, in particular, the ByteBuffer
. It can do all the work for you.
byte[] arr = { 0x00, 0x01 };
ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
short num = wrapped.getShort(); // 1
ByteBuffer dbuf = ByteBuffer.allocate(2);
dbuf.putShort(num);
byte[] bytes = dbuf.array(); // { 0, 1 }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…