byte array to short array and back again in java byte array to short array and back again in java arrays arrays

byte array to short array and back again in java


I also suggest you try ByteBuffer.

byte[] bytes = {};short[] shorts = new short[bytes.length/2];// to turn bytes to shorts as either big endian or little endian. ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);// to turn shorts back to bytes.byte[] bytes2 = new byte[shortsA.length * 2];ByteBuffer.wrap(bytes2).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(shortsA);


public short bytesToShort(byte[] bytes) {     return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getShort();}public byte[] shortToBytes(short value) {    return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(value).array();}


How about some ByteBuffers?

byte[] payload = new byte[]{0x7F,0x1B,0x10,0x11};ByteBuffer bb = ByteBuffer.wrap(payload).order(ByteOrder.BIG_ENDIAN);ShortBuffer sb = bb.asShortBuffer();while(sb.hasRemaining()){  System.out.println(sb.get());}