0

I want to convert a byte array to double and am doing this using the following code -

double fromByteArraytoDouble(byte[] bytes) {

    return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getDouble();
}

This code works, but I call this function in repeated iterations in my android app. (The loop is actually a background process that keeps running.) The wrap() function supposedly creates a new object everytime it is called and therefore after a few execution cycles the android garage collector runs to clean up the memory (I got this info from DDMS) -

 D/dalvikvm(6174): GC_FOR_ALLOC freed 2K, 5% free 12020K/12580K, paused 15ms, total 15ms

This pauses the code for some milliseconds which is unacceptable for the app. Is there a way to do the conversion of the byte array to double without using ByteBuffer?

abhishek
  • 817
  • 6
  • 19
  • 33

1 Answers1

2
long bits = 0L;
for (int i = 0; i < 8; i++) {
  bits |= (bytes[i] & 0xFFL) << (8 * i);
  // or the other way around, depending on endianness
}
return Double.longBitsToDouble(bits);
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Doesn't seem to be giving the correct value. Could be an endian issue. What do you mean, the other way around? Simply running i from 7 to 0 and changing nothing else? – abhishek Nov 15 '13 at 20:32
  • ok, got it working! The above works with big endian only if it is << 8*i, not just i. And for little endian, it changes to bits = (bits << 8) + (bytes[i] & 0xff); – abhishek Nov 15 '13 at 21:00