Convert short to byte[] in Java

前端 未结 9 685
旧巷少年郎
旧巷少年郎 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:25

    An alternative that is more efficient:

        // Little Endian
        ret[0] = (byte) x;
        ret[1] = (byte) (x >> 8);
    
        // Big Endian
        ret[0] = (byte) (x >> 8);
        ret[1] = (byte) x;
    

提交回复
热议问题