Convert short to byte[] in Java

JavaByteShort

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

ret[0] = (byte)(x & 0xff);
ret[1] = (byte)((x >> 8) & 0xff);

Solution 2 - Java

A cleaner, albeit far less efficient solution is:

ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putShort(value);
return buffer.array();

Keep this in mind when you have to do more complex byte transformations in the future. ByteBuffers are very powerful.

Solution 3 - Java

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;

Solution 4 - Java

Figured it out, its:

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

Solution 5 - Java

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())
}

Solution 6 - Java

Several methods have been mentioned here. But which one is the best? Here follows some proof that the following 3 approaches result in the same output for all values of a short

  // loops through all the values of a Short
  short i = Short.MIN_VALUE;
  do
  {
    // method 1: A SIMPLE SHIFT
    byte a1 = (byte) (i >> 8);
    byte a2 = (byte) i;

    // method 2: AN UNSIGNED SHIFT
    byte b1 = (byte) (i >>> 8);
    byte b2 = (byte) i;

    // method 3: SHIFT AND MASK
    byte c1 = (byte) (i >> 8 & 0xFF);
    byte c2 = (byte) (i & 0xFF);

    if (a1 != b1 || a1 != c1 ||
        a2 != b2 || a2 != c2)
    {
      // this point is never reached !!
    }
  } while (i++ != Short.MAX_VALUE);

Conclusion: less is more ?

byte b1 = (byte) (s >> 8);
byte b2 = (byte) s;

(As other answers have mentioned, watch out for LE/BE).

Solution 7 - Java

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;

Solution 8 - Java

public short bytesToShort(byte[] bytes) {
     return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getShort();
}

public byte[] shortToBytes(short value) {
	byte[] returnByteArray = new byte[2];
	returnByteArray[0] = (byte) (value & 0xff);
	returnByteArray[1] = (byte) ((value >>> 8) & 0xff);
	return returnByteArray;
}

Solution 9 - Java

short to byte

short x=17000;    
byte res[]=new byte[2];    
res[i]= (byte)(((short)(x>>7)) & ((short)0x7f) | 0x80 );    
res[i+1]= (byte)((x & ((short)0x7f)));

byte to short

short x=(short)(128*((byte)(res[i] &(byte)0x7f))+res[i+1]);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHughView Question on Stackoverflow
Solution 1 - JavaAlexander GesslerView Answer on Stackoverflow
Solution 2 - JavaGiliView Answer on Stackoverflow
Solution 3 - JavaDavidView Answer on Stackoverflow
Solution 4 - JavaHughView Answer on Stackoverflow
Solution 5 - JavaSerg BurlakaView Answer on Stackoverflow
Solution 6 - JavabvdbView Answer on Stackoverflow
Solution 7 - JavaabcView Answer on Stackoverflow
Solution 8 - JavaScott IzuView Answer on Stackoverflow
Solution 9 - Javachitrendra chaudharyView Answer on Stackoverflow