I know a quick way to convert a byte/short/int/long array to ByteBuffer, and then obtain a byte array. For instance, to convert a byte array to short array I can do:
byte[] bArray = { 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 };
ByteBuffer bb = ByteBuffer.wrap(byteArray);
ShortBuffer sb = bb.asShortBuffer();
short[] shortArray = new short[byteArray.length / 2];
sb.get(shortArray);
produces a short array like this: [256, 0, 0, 0, 256, 0, 0, 0].
How can I do the inverse operation using java.nio classes?
Now I am doing this:
shortArray[] = {256, 0, 0, 0, 256, 0, 0, 0};
ByteBuffer bb = ByteBuffer.allocate(shortArray.length * 2);
for (short s : shortArray) {
bb.putShort(s);
}
return bb.array();
And I obtain the original [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] byte array. But I want to use a method like ShortBuffer.asByteBuffer(), not a manual loop to do it.
I have found a request to Sun of 2001, but they did not accept it ;-((
What about this? :
Then
bbcontains your data.Full code: