Reputation: 290
Can someone please let me know how to convert a a ByteBuffer into a long[]?
I had a long[] to begin with, which I converted to a ByteBuffer using the following piece of code:
byte[] convertToByteArray(long[] data) {
ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 8);;
LongBuffer longBuffer = byteBuffer.asLongBuffer();
longBuffer.put(data);
return byteBuffer.array();
}
I would now like to do the reverse, and write a few tests comparing the various arrays before and after conversion.
I tried the following, but it fails with an NPE on JDK 1.6.0_26:
long[] convertToLongArray(byte[] bArray) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bArray);
LongBuffer longBuffer = byteBuffer.asLongBuffer();
return longBuffer.array();
}
Regards, Roshan
Upvotes: 2
Views: 4139
Reputation: 1489
on my side it throws
Exception in thread "main" java.lang.UnsupportedOperationException
at java.nio.LongBuffer.array(LongBuffer.java:994)
at test.convertToLongArray(test.java:11)
at test.main(test.java:15)
It does that because the instance returned by byteBuffer.asLongBuffer()
call is a ByteBufferAsLongBufferL
or ByteBufferAsLongBufferB
class (depending on the indianess).
Both of these 2 classes are sub-classes of LongBuffer and inside the constructor call super
constructor is called without the long array parameter.
As @Kayaman mentioned, these are only views for the byte array from ByteBuffer.
Below is the super constructor called from the ByteBufferAsLongBufferL
constructor. Notice the null
parameter.
LongBuffer(int mark, int pos, int lim, int cap) { // package-private
this(mark, pos, lim, cap, null, 0);
}
The best option is to do this:
long[] convertToLongArray(byte[] bArray) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bArray);
LongBuffer longBuffer = byteBuffer.asLongBuffer();
long l[] = new long[longBuffer.capacity()];
longBuffer.get(l);
return l;
}
Upvotes: 3