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();
WWJD
  • 1,104
  • 4
  • 12
  • 31

2 Answers2

6
ByteBuffer.wrap(array).getFloat();
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
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)
}
Community
  • 1
  • 1
youssefhassan
  • 1,067
  • 2
  • 11
  • 17
  • You are casting int to float in the second method. Should use Float.intBitsToFloat(int bits). – RoK Jun 22 '23 at 04:48