0

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.

1 Answers1

1

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() {
  
}
JohnFilleau
  • 4,045
  • 1
  • 15
  • 22
  • 1
    It works very well! Thank you so much. //:D_b However, there is one caveat for those who use this code. There may be cases where the data in the hex[4] array is inverted. (not Big end) In that case, you can save and use the data in reverse order in the loop. – WooJae You Jul 24 '20 at 03:44
  • On this caveat - big endian or little endian isn't random, and whichever architecture (processor) you're building for will have its endianess documented. If you come across this and don't know whether your system is big or little endian, look it up in the documentation! – JohnFilleau Jul 24 '20 at 23:59