➦ You can use the unpack() method to convert bytes to floating point numbers. The method accepts data format and the byte to be converted. ➦ On the other hand, the pack() method helps in converting data types to bytes.
Float to Byte Array Conversion 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.
A consecutive sequence of variables of the data type byte, in computer programming, is known as a byte array. An array is one of the most basic data structures, and a byte is the smallest standard scalar type in most programming languages.
The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes).
I have a program that needs to take in 4 bytes and convert them to an IEEE-754 float. The bytes are transferred out of order, but I can put them back in order just fine. My problem is casting them to a float. The relevant parts of code:
//Union to store bytes and float on top of each other
typedef union {
unsigned char b[4];
float f;
} bfloat;
//Create instance of the union
bfloat Temperature;
//Add float data using transmitted bytes
MMI.Temperature.b[2] = 0xD1;//MMIResponseMsg[7];
MMI.Temperature.b[3] = 0xE1;//MMIResponseMsg[8];
MMI.Temperature.b[0] = 0x41;//MMIResponseMsg[9];
MMI.Temperature.b[1] = 0xD7;//MMIResponseMsg[10];
//Attempting to read the float value
lWhole=(long) ((float)MMI.Temperature.f);
//DEBUGGING
stevenFloat = (float)MMI.Temperature.f;
lWhole
is a long and stevenFloat
is a float. When debugging I can see that the values I assign to the byte array are being stored correctly, however the values of stevenFloat
and lWhole
are incorrect. They seem to hover close to 0, or close to the max float/long values. A long and float are both 32 bits with my compiler.
Does anyone know why this isn't working? It looked correct to me when I received the code to work on and it appears to be a common solution online, I am just stumped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With