-1

I want to convert my float variables into HEX value like 0x00466 or etc. but when I try all the things that I saw in the internet my Serial Console just turns out crazy :D like "' #gA".

I tried this code below

  float gyrox, gyroy, gyroz, accelx, accely, accelz, enlem, boylam, sicaklik, yukseklik, basinc;
  byte ByteArray[11];
  void setup() {
      Serial.begin(9600);
      gyrox = 1.5;
      gyroy = 2.5;
      gyroz = 2.0;
      accelx = 5.3;
      accely = 3.2;
      accelz = 6.1;
      enlem = 39.9250506;
      boylam = 32.8369756;
      sicaklik = 35.0;
      yukseklik = 103.0;
      basinc = 65.31455;

      ByteArray[0]=(gyrox,HEX);
      ByteArray[1]=(gyroy,HEX);
      ByteArray[2]=(gyroz,HEX);
      ByteArray[3]=(accelx,HEX);
      ByteArray[4]=(accely,HEX);
      ByteArray[5]=(accelz,HEX);
      ByteArray[6]=(enlem,HEX);
      ByteArray[7]=(boylam,HEX);
      ByteArray[8]=(sicaklik,HEX);
      ByteArray[9]=(yukseklik,HEX);
      ByteArray[10]=(basinc,HEX);
  }

  void loop() {
    Serial.println((char*)ByteArray);
  }

and the result is ""(:D) I want the result like "0x000466 or anything likte HEX value" so what should I do?

  • A float is stored in 4-byte in according to IEEE754, To get the LSB byte (little endian), do `Serial.print(((uint8_t*)&gyrox)[0], HEX);`. For gyrox=1.5, you should get a byte array of 0x00, 0x00, 0xC0, 0x3F, with 0x34 as the MSB. – hcheung Jan 17 '23 at 13:46

2 Answers2

0

You can cast the float to an array of bytes to get its internal representation. Then you can loop over all of the bytes and print each of them individually.

void printFloat(float const f)
{
  // cast the float to an array of bytes
  uint8_t const * const byteArray = (uint8_t const *)&f;
  // print the start
  Serial.print("0x");
  // loop over the bytes, sizeof(f) tells us how many bytes make up the float
  for (size_t idx = 0; idx != sizeof(f); ++idx)
  {
    // get the byte for this position
    uint8_t const b = byteArray[idx];
    // print a zero if b < 16,
    // https://stackoverflow.com/questions/19127945/how-to-serial-print-full-hexadecimal-bytes
    Serial.print(b>>4,  HEX);
    Serial.print(b&0x0F,HEX);
  }
}
Lanting
  • 3,060
  • 12
  • 28
0

A float is 32 bits long (4 bytes). You can try this:

float f;
Serial.print("0x"); Serial.print(*(uint32_t*)&f, HEX);

If you really need leading zeroes, try this:

void hex_print(uint32_t x)
{
    Serial.print("0x");
    for (uint32_t mask = 0x0FFFFFFFul; mask && mask > x; mask >>= 4)
        Serial.print('0');
    Serial.print(x, HEX);
}


// calling as:
float f = 123.456f;
hex_print(*(uint32_t*)&f);
Michaël Roy
  • 6,338
  • 1
  • 15
  • 19