You only work with signed 16-bit data. So why do you go through (and return) an int rather than short ? You discard information about the sign, so this will not work on negative numbers. Instead, use short and everything will be fine - and additional type information will make your code more secure.
byte[] ShortToBytes(short i) { return new byte [] {(byte) ((i >> 8) & 0xff), (byte) (i & 0xff)}; } short BytesToShort(byte hi, byte lo) { return unchecked((short)((hi << 8) | lo)); }
The main advantage (besides clarity and actual operation) is that you can no longer pass an invalid value to a method. This is always good :)
Oh, and I would recommend maintaining a symmetrical interface - BytesToShort should also take byte[] (or another structure that has two bytes).
Luaan source share