Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java byte array to ByteBuffer or ByteBuffer to byte array convertion "WITHOUT COPYING"

the biggest problem on java arrays , they require copying to edit. I am using AMD Aparapi , which i get byte array from my calculations. I need to show that byte array as a bytebuffer "without copying"

byte aparapiData[];
ByteBuffer buffer;
...
//here bytebuffer
buffer.clear();
buffer.put(aparapiData);
buffer.flip();

socket.write(buffer);

The problem here on code , buffer.put is copying byte array to bytebuffer. And also there is reverse problem to convert byte array to bytebuffer.

Are they really require copying data? I can send pure data on C++ without copying.

How can i solve this issue on Java ?

like image 597
Kadir BASOL Avatar asked Jun 26 '15 00:06

Kadir BASOL


1 Answers

To get a ByteBuffer that points to an existing byte array, you can use the wrap function:

byte[] array = /* something */;
ByteBuffer buffer = ByteBuffer.wrap(array);

To get a byte array that points to an existing ByteBuffer, you can use the array method:

ByteBuffer buffer = /* something */;
byte[] array = buffer.array();

However, note that the latter only works when the ByteBuffer is backed by an array (i.e. if hasArray returns true).

The reason for this lack of symmetry is that a ByteBuffer could be implemented in any number of different ways. Sometimes it is implemented as just an array in memory, but it's quite possible that it could read data from the disk or from the network or from some other source when queried. In this case, you can't just access the underlying array because there is none.

like image 103
Sam Estep Avatar answered Sep 18 '22 12:09

Sam Estep