Kasper
Kasper

Reputation: 690

From 32 + 32 bit to double

for some reason I need to retrieve a double value from two 32 bit. Let me explain: On the server side they send a double value formatted like this:

  // C/C++ = SERVER 
  double big;
  big = 12345.67890;
  unsigned int *pi = (unsigned int *)&big;

  unsigned int x = pi[0];
  unsigned int y = pi[1];

they send from the server to the client a double formatted with two unsigned int (x and y, 32 bit each in my case). On the client side (JAVA) I need to build again the double value from the two unsigned integers received. I tried this without success:

// double double64 = buffer2.getDouble();
ByteBuffer buffer = ByteBuffer.allocate(16);
buffer.putLong(my_int_x);
buffer.putLong(my_int_y);
buffer.flip();
double double64 = buffer.getDouble();

maybe because I'm receiving a 32 bit integer and I use "putLong"?

Upvotes: 1

Views: 145

Answers (1)

fernacolo
fernacolo

Reputation: 7439

To convert two ints (containing double data) into a double, you don't need a temporary buffer. You can do this:

long doubleBits = my_int_x & 0xFFFFFFFFL;
doubleBits <<= 32;
doubleBits |= my_int_y & 0xFFFFFFFFL;
double myDouble = Double.longBitsToDouble(doubleBits);

However, check how you are reading my_int_x and my_int_y in your Java program. Maybe you can get a double directly at that moment (ideally, you should).

Upvotes: 4

Related Questions