Reputation: 927
My Java application will receive little-endian short[] data through socket communication. Java by default is big-endian. But I want to keep these shorts in little-endian.
If I define a short[] to receive the data, will the Java automatically convert them from little-endian to big-endian when the data is put into the short[]?
do I need to do anything to keep the received data in the format of little-endian?
Upvotes: 0
Views: 867
Reputation: 3157
Summary
Java will not automatically convert bytes to a short, although you can explicitly tell Java to convert them. You cannot force Java to interpret its own shorts as little-endian numbers. You can, however, write Java shorts as little-endian shorts.
Detail
When you say that you're receiving an array of little-endian shorts, I'm assuming that you mean that you're receiving a series of bytes, that you divide the series into pairs, and that the first of the pair is the least-significant byte of a short and the second of which is the most-significant byte.
I don't believe that Java will know how to interpret those bytes unless you explicitly tell it.
For example, if you use java.io.DataInputStream.readShort
it will read "the next two bytes of this input stream, interpreted as a signed 16-bit number" - and, while this documentation doesn't say, it will interpret the short in the Java way, which is big-endian.
As noted in the comment, if you wish to read a little-endian short into a Java short, you may use java.nio.ByteBuffer
: wrap
the byte array, set the order
to LITTLE_ENDIAN
, and invoke getShort
. However, this will store the data as a Java short, which is big-endian. You cannot change that storage format.
You can, however, write a Java short as a little-endian short using the same java.nio.ByteBuffer
: wrap
the byte array, set the order
to LITTLE_ENDIAN
, and invoke putShort
.
Upvotes: 3