Convert short to byte[] in Java

Hugh picture Hugh · Feb 3, 2010 · Viewed 91.2k times · Source

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 something like this. But not sure.

((0xFF << 8) & x) >> 0;

EDIT:

Also you can use:

java.nio.ByteOrder.nativeOrder();

To discover to get whether the native bit order is big or small. In addition the following code is taken from java.io.Bits which does:

  • byte (array/offset) to boolean
  • byte array to char
  • byte array to short
  • byte array to int
  • byte array to float
  • byte array to long
  • byte array to double

And visa versa.

Answer

Alexander Gessler picture Alexander Gessler · Feb 3, 2010
ret[0] = (byte)(x & 0xff);
ret[1] = (byte)((x >> 8) & 0xff);