I would advice to use Google Protocol Buffers: https://developers.google.com/protocol-buffers/docs/overview It has libs for C and Java and many other languages, like for example Python, which you may find useful later. It is efficient, robust, will take care of endianness, etc.
How to send c++ doubles from one system to another Sender: Winsock Receiver: Java
-
09-03-2022 - |
Domanda
The sending C-side
double tmp = htonl(anydouble);
send(socket, (char *) &tmp, sizeof(tmp), 0);
On the Java side, im reading the network data into a char[8]
What is the proper way of performing the conversion back to double? Is it the way to go to simply send a string and parse it back to double?
Soluzione 2
Altri suggerimenti
This should work.
char[] sentDouble = readBytes(); // get your bytes char[8]
String asString = new String(sentDouble); // make a string out of it
double myDouble = Double.parseDouble(asString); // parse it into a double
With a byte[] you can do
import java.nio.ByteBuffer;
public static double toDouble(byte[] bytes) {
return ByteBuffer.wrap(bytes).getDouble();
}
You're reinterpreting a double as a long. This won't be portable. Here are some alternatives:
- do you really need to use floating point values? Can you represent your values as integers (e.g. milliseconds instead of seconds)?
- encode the double as a string (e.g. sprintf and Double.parseDouble)
- extract mantissa and exponent with frexp and send as integers, then convert back in Java with Double.longBitsToDouble
There's no need for String
overhead. Assemble the bytes into a long
first, then use Double's static longBitsToDouble method.
// The bit pattern for the double "1.0", assuming most signficant bit first in array.
char[] charArray = new char[] {0x3F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
long bytesAsLong = 0L;
for (int i = 0; i < 8; i++)
{
bytesAsLong |= ((long) charArray[i] << (56 - 8*i));
}
double value = Double.longBitsToDouble(bytesAsLong);
System.out.println(value); // prints "1.0"
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow