Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert 4 bytes array to float in java

I have a 4 bytes array which represent a float value. The bytes is read from network, for example, 3e 3f e3 a0. How can I convert it from byte[] to float in java?

like image 210
Aaron Avatar asked Nov 20 '12 09:11

Aaron


People also ask

How do you convert Bytearray to long?

Similarly, the BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes). longValue();

Can we convert byte array to file in Java?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.

How do you convert a float to a byte?

As we know, the size of a float in Java is 32 bit which is similar to an int. So we can use floatToIntBits or floatToRawIntBits functions available in the Float class of Java. And then shift the bits to return a byte array.


2 Answers

In Java a char is 16-bit. If you mean you have a 4 byte values in little endian byte order which you need to convert to a float you can use ByteBuffer.

byte[] bytes = { } float f = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat(); 
like image 81
Peter Lawrey Avatar answered Sep 26 '22 03:09

Peter Lawrey


Try this:

float foo = Float.intBitsToFloat( buffer[n] ^ buffer[n+1]<<8 ^ buffer[n+2]<<16 ^ buffer[n+3]<<24 );

like image 33
Xavier Avatar answered Sep 25 '22 03:09

Xavier