Search code examples
c++arduinofloating-pointbyte

Proper Way to Convert Byte Array to Float? (Arduino)


I'm attempting to convert an array of 4 byte values to a single float value in Arduino.

I'm using a union in order to store my values, and I'm able to convert a long to a float that way.

Here's the code:

union value {
  float f;
  unsigned long l;
  byte b[4];
} value;

void setup() 
{
  Serial.begin(9600);

  // Setting 105.00 to the value variable via modifying the field "l"
  value.l = 0x42D20000;
  Serial.println("\nFloat value: " + String(value.f));
  Serial.print("Byte values: {");

  for (int i = 0; i < 4; i++) 
  {
    Serial.print(value.b[i], HEX);
    Serial.print(", ");
  }
  
  Serial.println("}");
  
  // Setting 4.55 to the value variable via modifying the field "b"
  value.b[0] = 0X40;
  value.b[1] = 0X91;
  value.b[2] = 0X99;
  value.b[3] = 0X9A;
  
  Serial.println("Float value: " + String(value.f));
  Serial.print("Byte values: {");

  for (int i = 0; i < 4; i++) 
  {
    Serial.print(value.b[i], HEX);
    Serial.print(", ");
  }

  Serial.println("}");
}

void loop()
{
}

I first try to assing the value of 105 to the l field, and then read the f field. That appears to be successful, and I get the desired 105.00 in the f field if I try to read from it.

However, I subsequently want to assign a value of 4.55 to my f field by assigning each byte entry in the b array field. That does not appear to work, and I am left with a value of -0.00 in the f field if I try to read from it.

This is current output of the code shown above:

Float value: 105.00
Byte values: {0, 0, D2, 42, }
Float value: -0.00
Byte values: {40, 91, 99, 9A, }

While the individual bytes are saved successfully in the b field, the f field does not appear to update automatically.

Any ideas as to why I'm not able to get 4.55 as my f field in the latter half of the code above?

Thanks for reading my post, any guidance is appreciated.


Solution

  • The CPU is probably little-endian, which means the least-significant byte is stored at the beginning.

    Have you tried this:

    value.b[3] = 0X40;
    value.b[2] = 0X91;
    value.b[1] = 0X99;
    value.b[0] = 0X9A;