Combining bytes as an integer or short sign

I know that I can extract bytes from int as follows:

bytes[] IntToBytes(int i) { return new byte [] {(byte) ((i >> 8) & 0xff), (byte) (i & 0xff)}; } 

which I subsequently ship as part of a serial transmission. But can I do the opposite, having received a sequence of bytes, restore the original data, retaining the sign. I'm currently doing this, but it feels a bit on top:

 int BytesToInt( byte hi, byte lo) { return ((hi << 24) | (lo << 16)) >> 16; } 

Is there any other way or better way? Does it really matter if I know that in the end I only deal with signed 16-bit data?

+6
source share
1 answer

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).

+2
source

Source: https://habr.com/ru/post/985184/


All Articles