8 years ago.

How to convert a float variable to hex

Hello, how can I convert a float variable to hex? I need it to use as less bytes as possible

Thank you

1 Answer

8 years ago.

In what context? If you are storing it in internal memory or a file then it's already as compact as it's going to get, a float will take up 32 bits.

To output it over a serial link? The easiest way is to treat it as if it was an array of 4 bytes and send them as raw binary.

Sending:

void outputFloat(float value) {
  unsigned char * charPtr = (unsigned char*)&value;  // create a char * that points to the location of value
  for (int i = 0; i<4; i++) {    // each byte in value
    pc.putc(*(charPtr + i));  // send the next value pointed to by charPtr it over the serial port.
  }
}

Receiving:

float readFloat(void) {
  unsigned char dataIn[4];   // create an array to store the data
  for (int i = 0; i<4; i++) {
    dataIn[i] = pc.getc();       // read 4 bytes into the array
  }
  return *((float *)(dataIn));  // treat the array address as a float pointer and return the value it points to.
}

Thank you for your answer.

I'm storing it in internal memory to send it later, i need it in Hex because of the receiver

Thank you

posted by Javier Sing 06 Dec 2016

Then store it as a float. There is no point in messing around with casting between data types if you are storing it in memory, the standard format is the most efficient. No matter what you do a 32 bit float will take up 32 bits. Arrays don't have any memory overhead so bulk storage is simple.

The only way you can improve things is if you make assumptions about the possible values. e.g. if it's always going to be between 0 and 100 and you only need 2 decimal places accuracy then multiply by 100, add 0.5 and convert the result to a uint16_t. That would give you 2 decimal places accuracy for values between 0 and 655.

posted by Andy A 06 Dec 2016

Thank you for your time Andy

But as I said, I need to convert the variables from float to Hex

posted by Javier Sing 06 Dec 2016

You aren't making any sense. Hex is a way of writing binary values in text. It takes up twice as much space as storing the same value in binary. Do you need to store it as text or in as compact format as possible?

posted by Andy A 06 Dec 2016

I need it in Hex

posted by Javier Sing 06 Dec 2016

You mean as a text string e.g. 0xAF? Because that's what hex is. If so change the putc in the original answer to printf("%02X", *(charPtr + i));

posted by Andy A 06 Dec 2016

I've tried this:

void float2Hex(float value) { int decimal; int entero; char value2[8]; entero = value; decimal = (value - entero)*16; unsigned short enteroh= entero; unsigned short decimalh = decimal; sprintf(value2, "%X.%X", enteroh,decimalh); }

because I need to transform floats and store the new variables

posted by Javier Sing 06 Dec 2016