Int to float convertion[Solved]

Hi @oyel,

the recommended way to convert the binary floating point representation back to a floating point variable is the use of memcpy:

uint32_t binaryFloat32   =  0x41C347AEUL;
float mcpyVal            = 0;


void setup() {
  Serial.begin(115200);
  Serial.print("Binary Float Value:\t0x");
  Serial.println(binaryFloat32,HEX);

  // use of memcpy -> Recommended!
  memcpy (&mcpyVal,&binaryFloat32,sizeof (binaryFloat32));
  Serial.print("Memcopy result:   \t");
  Serial.println(mcpyVal);  
}

void loop() {
}

There are some other methods as well but they are not considered safe due to possible compiler optimization (if I understood it correctly: see here for example https://forum.arduino.cc/t/is-this-illegal-type-punning/1068033/56

Your question regarding the union you may find answers here
https://en.cppreference.com/w/cpp/language/union

In a nutshell: A number of variables share the same space in memory. Any member of that union uses the space as if only this member had access:

union binaryfloat {
     float floating;  // single-precision float using 4 bytes
     uint32_t integer; // unsigned integer using 4 bytes
} unionVal;

So writing and reading whether using unionVal.floating or unionVal.integer will always use all four bytes. This method is valid in C but not in C++ (extract from https://en.wikipedia.org/wiki/Type_punning#cite_ref-8 ):

The same is syntactically valid but has undefined behavior in C++, [8] however, where only the last-written member of a union is considered to have any value at all.

This restriction is clear but - to my understanding - should have no negative influence if both members inside the union always use the full range of available bytes ...