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.
You can simply iterate the byte array and print the byte using System. out. println() method.
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)};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With