Reputation: 1721
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?
Upvotes: 2
Views: 4264
Reputation: 136162
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();
}
Upvotes: 7
Reputation: 16168
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.
Upvotes: 4
Reputation: 1159
apache httpcore provides a org.apache.http.util.ByteArrayBuffer class which my be helpful
ByteArrayBuffer buffer = new ByteArrayBuffer(26);
buffer.append(...)
Upvotes: 1