0

I want to convert a 4-element byte array which I receive from socket connection to float. I searched on Google and tried several methods but couldn't help myself.

UPDATE The proper way to convert byte array to float is using this code:

ByteBuffer.wrap(array).getFloat();
3
  • stackoverflow.com/questions/13469681/… Commented Mar 7, 2014 at 13:09
  • 1
    What are the methods you tried and how they didn't work? Commented Mar 7, 2014 at 13:13
  • I tried float f = ByteBuffer.wrap(size).order(ByteOrder.LITTLE_ENDIAN).getFloat(); but it doesn't return what I expected. Commented Mar 7, 2014 at 13:23

2 Answers 2

6
ByteBuffer.wrap(array).getFloat();
Sign up to request clarification or add additional context in comments.

Comments

1

Refer to this question , Use these methods:

float fromByteArray(byte[] bytes) {
     return ByteBuffer.wrap(bytes).getFloat();
}

float fromByteArray(byte[] bytes) {
     return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF)
}

1 Comment

You are casting int to float in the second method. Should use Float.intBitsToFloat(int bits).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.