Convert short to byte[] in Java

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

    Figured it out, its:

    public static byte[] toBytes(short s) {
        return new byte[]{(byte)(s & 0x00FF),(byte)((s & 0xFF00)>>8)};
    }
    

提交回复
热议问题