Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

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);
share|improve this answer
    
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.