Convert short to byte array (and byte array to short)

It was very hard to find something that worked, so finally I found something that worked and passed my tests by combining some sources online and modifying it a bit. This conversion is aims to be compatible with JavaCard’s Util.setShort, Util.getShort and Util.makeShort.

public static short readShort(byte[] data, int offset) {
	return (short) (((data[offset] << 8)) | ((data[offset + 1] & 0xff)));
}

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

The tests I performed (convert short to byte array and then back and compare):

0 -> 0x00 0x00  -> 0 ---> OK
1 -> 0x00 0x01  -> 1 ---> OK
-1 -> 0xFF 0xFF  -> -1 ---> OK
100 -> 0x00 0x64  -> 100 ---> OK
255 -> 0x00 0xFF  -> 255 ---> OK
256 -> 0x01 0x00  -> 256 ---> OK
-256 -> 0xFF 0x00  -> -256 ---> OK
32767 -> 0x7F 0xFF  -> 32767 ---> OK
-32768 -> 0x80 0x00  -> -32768 ---> OK
-255 -> 0xFF 0x01  -> -255 ---> OK

Hope it helps at least someone else🙂

4 thoughts on “Convert short to byte array (and byte array to short)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s