Convert short to byte[] in Java

前端 未结 9 659
旧巷少年郎
旧巷少年郎 2020-11-30 03:48

How can I convert a short (2 bytes) to a byte array in Java, e.g.

short x = 233;
byte[] ret = new byte[2];

...

it should be s

相关标签:
9条回答
  • 2020-11-30 04:03
    public short bytesToShort(byte[] bytes) {
         return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getShort();
    }
    
    public byte[] shortToBytes(short value) {
        byte[] returnByteArray = new byte[2];
        returnByteArray[0] = (byte) (value & 0xff);
        returnByteArray[1] = (byte) ((value >>> 8) & 0xff);
        return returnByteArray;
    }
    
    0 讨论(0)
  • 2020-11-30 04:07

    A cleaner, albeit far less efficient solution is:

    ByteBuffer buffer = ByteBuffer.allocate(2);
    buffer.putShort(value);
    return buffer.array();
    

    Keep this in mind when you have to do more complex byte transformations in the future. ByteBuffers are very powerful.

    0 讨论(0)
  • 2020-11-30 04:08
    ret[0] = (byte)(x & 0xff);
    ret[1] = (byte)((x >> 8) & 0xff);
    
    0 讨论(0)
  • 2020-11-30 04:11

    Short to bytes convert method In Kotlin works for me:

     fun toBytes(s: Short): ByteArray {
        return byteArrayOf((s.toInt() and 0x00FF).toByte(), ((s.toInt() and 0xFF00) shr (8)).toByte())
    }
    
    0 讨论(0)
  • 2020-11-30 04:13

    Figured it out, its:

    public static byte[] toBytes(short s) {
        return new byte[]{(byte)(s & 0x00FF),(byte)((s & 0xFF00)>>8)};
    }
    
    0 讨论(0)
  • 2020-11-30 04:14

    short to byte

    short x=17000;    
    byte res[]=new byte[2];    
    res[i]= (byte)(((short)(x>>7)) & ((short)0x7f) | 0x80 );    
    res[i+1]= (byte)((x & ((short)0x7f)));
    

    byte to short

    short x=(short)(128*((byte)(res[i] &(byte)0x7f))+res[i+1]);
    
    0 讨论(0)
提交回复
热议问题