How can I handle the underlying byte array as an array of shorts? Or ints? Or thirst?

I am a built-in engineer working in Java. I need to communicate with devices, and often I need to massage the buffers in the form necessary or produced by some equipment.

I spent a lot of time searching the network (and on this site) for the answer to the question of how to handle the byte buffer as a buffer of larger elements. There are many answers, but they always come down to (1) using ByteBuffer or (2) doing the conversion manually.

The problem is that no conversion is needed ... the underlying byte array contains valid shorts with the correct precision. I do not want the cost of copying an array of bytes to the same set of shorts. All I want to do is convince the Java compiler to see them as the type that interests me.

I do not have much experience with ByteBuffer, but this was the first path I took. I found that if I have ByteBuffer and I call its asShortBuffer () function, as a result, ShortBuffer does not have a backup array ... I cannot call array () on it, which is what I need.

Any thoughts?

+4
source share
4 answers

Do you really need a ShortBuffer? Why not just use the various get / put methods in ByteBuffer to read / write short, int and other values ​​from / to the underlying byte array?

+1
source

I really don’t know your usecase, but the question does not mean that you really need to convert the entire byte array to an array of shorts / ints / longs (otherwise a ByteBuffer or manuall conversion would be fine).

If you just need to treat any value in this array as short / int / long, all you have to do is assign it and the upcast will be implicit:

int i = byteArray[x]; // works like a charm 

In the same way, you can pass any value there to a method that expects long or something else, without the need for casting.


Edit:

As an answer to your comment, you can only use array covariance if you can allow the use of object wrappers instead of primitives (this implies that you control the code in the method you specify):

 // needs to be Number because Byte does not inherit from Short myMethod(Number[] numbers) { // do something with number.shortValue() ... 

And you can call it using:

 myMethod(new Byte[10]); 

But that would be even less acceptable than assuming the conversion of a byte[] to short[] .

+1
source

Instead of making array () from ShortBuffer, you can simply use get () array in existing array. The same can be applied to other data types.

0
source

If you have a byte buffer and you know endainness, you can always generate shorts / ints on the fly. You are stuck because you want to access it as an array of shorts / ints.

0
source

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


All Articles