tags:

views:

964

answers:

3

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.

+4  A: 
ret[0] = (byte)(x & 0xff);
ret[1] = (byte)((x >> 8) & 0xff);
Alexander Gessler
Ah thanks. I have posted a method too.
Hugh
That's little endian, though. Network byte-order is big endian: 'byte[] arr=new byte[]{(byte)((x>>8)
Software Monkey
A: 

Figure it out its.

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

It depends how you want to represent it:

  • big endian or little endian? That will determine which order you put the bytes in.

  • Do you want to use 2's complement or some other way of representing a negative number? You should use a scheme that has the same range as the short in java to have a 1-to-1 mapping.

For big endian, the transformation should be along the lines of: ret[0] = x/256; ret[1] = x%256;

abc