Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert short to byte[] in Java

Tags:

java

byte

short

People also ask

What does byte [] do in Java?

The Java byte keyword is a primitive data type. It is used to declare variables. It can also be used with methods to return byte value. It can hold an 8-bit signed two's complement integer.

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.

Can we convert string to byte array in Java?

The String class provides three overloaded getBytes methods to encode a String into a byte array: getBytes() – encodes using platform's default charset. getBytes (String charsetName) – encodes using the named charset. getBytes (Charset charset) – encodes using the provided charset.


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

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.


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;

Figured it out, its:

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