1

In past I haven't done much of byte shifting so I'm a bit loss here. Basically I have double array of size 26 and I should send the array in one UDP packet in Java. I found some examples of how to convert one double to bytearray, but I'm not sure how to apply it to double-array.

So how this should be done? Loop through the double array and convert each double and somehow concatenating them to one bytearray?

Tumetsu
  • 1,661
  • 2
  • 17
  • 29
  • 2
    I think you want to start with reading about [`DoubleBuffer`](http://docs.oracle.com/javase/6/docs/api/java/nio/DoubleBuffer.html). Better yet, start with the method [ByteBuffer#asDoubleBuffer](http://docs.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html#asDoubleBuffer()) – Marko Topolnik Jun 03 '13 at 08:23
  • If you know how to do it once and have to do it 26 times, why no use a `for` loop? – Djon Jun 03 '13 at 08:24

3 Answers3

6

Convert your doubles into a byte array using java.nio.ByteBuffer

ByteBuffer bb = ByteBuffer.allocate(doubles.length * 8);
for(double d : doubles) {
   bb.putDouble(d);
}

get the byte array

byte[] bytearray = bb.array();

send it over the net and then convert it to double array on the receiving side

ByteBuffer bb = ByteBuffer.wrap(bytearray);
double[] doubles = new double(bytearray.length / 8);
for(int i = 0; i < doubles.length; i++) {
    doubles[i] = bb.getDouble();
}
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
4

So how this should be done? Loop through the double array and convert each double and somehow concatenating them to one bytearray?

Exactly. You can make use of DoubleBuffer, perhaps. (Marko linked it in his comment)

What Marko referred to was having actually a ByteBuffer and fetching a "DoubleBuffer"-View to it. So you can put the Doubles into the DoubleBuffer View and fetch the byte[] from the original ByteBuffer.

Fildor
  • 14,510
  • 4
  • 35
  • 67
  • I always thought about java.nio being rather low-level, but it is much more .. see http://en.wikipedia.org/wiki/New_I/O - thanks to Fildor – Steve Oh Jun 03 '13 at 08:34
  • Ah, bytebuffer was exactly what I was missing here! Thanks for you and Marko for pointing that out. – Tumetsu Jun 03 '13 at 10:31
1

apache httpcore provides a org.apache.http.util.ByteArrayBuffer class which my be helpful

ByteArrayBuffer buffer = new ByteArrayBuffer(26);
buffer.append(...)
Steve Oh
  • 1,149
  • 10
  • 18