arduino32-bitieee-754single-precision

Arduino convert float to hex IEEE754 Single precision 32-bit


I would like to convert float values ​​to IEEE754 Single precision 32-bit Hex values ​​in the following site on Arduino. https://www.binaryconvert.com/result_float.html?decimal=051046049048

float f = 3.10;
byte hex[4] = {0};

byte FloatToHex(float f){
   .......
}

How can I create a function like this? It's okay if the format is different.


Solution

  • f is already stored in binary. reinterpret_cast is generally a code smell issue, but its valid use is to view the byte representation of variables.

    
    void FloatToHex(float f, byte* hex){
      byte* f_byte = reinterpret_cast<byte*>(&f);
      memcpy(hex, f_byte, 4);
    }
    
    void setup() {
      float f = 3.10;
      byte hex[4] = {0};
    
      FloatToHex(f, hex);
      //... do stuff with hex now...
    }
    
    void loop() {
      
    }