문제

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?

도움이 되었습니까?

해결책 2

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.

다른 팁

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"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top