I am communicating with some device and this device sending me data as unsigned bytes. And I need to convert these bytes to float in Java. Is there any way?
Thank you very much.
Yes. Float.intBitsToFloat
takes 32 bits as an int and converts it to a float.
All you need to do first is convert your four bytes to an int
using the normal shift and or operations appropriate to the endianness of your data. For example,
float f = Float.intBitsToFloat(
(barr[0] & 0xff)
| ((barr[1] & 0xff) << 8)
| ((barr[2] & 0xff) << 16)
| ((barr[7] & 0xff) << 24));
You can also use FloatBuffer
depending on how you are receiving the data.
public abstract FloatBuffer asFloatBuffer()
Creates a view of this byte buffer as a float buffer.
Note, that "the device [is] sending me data as unsigned bytes" is not true. The data is sending you bytes, and Java represents them as signed bytes. Java does not have an unsigned byte type.
http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).