Convert short to byte[] in Java

前端 未结 9 696
旧巷少年郎
旧巷少年郎 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: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())
    }
    

提交回复
热议问题