Convert short to byte[] in Java

前端 未结 9 702
旧巷少年郎
旧巷少年郎 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: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]);
    

提交回复
热议问题