# hexadecimal 1 to float 1 - Compare the float 1 with a predefined float 2 - If the float 1 and float 2 are the same - Print hexadecimal 2

I want to input a hexadecimal data from cool terminal say like (05 00 02 03 00 04 00 E5) And convert the data to a float value say 45.3. Now that I have to preassign a float value say 45.3 in my program so that I can compare the converted float value with the preassigned float value. If the two values match I need to print another hexadecimal value i.e( 05 03 00 01 00 02 04 4F).

• In what format are you sending the float over serial? ASCII encoded decimal number? ASCII encoded hexadecimal number? binary? Currently you are reading ASCII encoded decimal. – chrisl Dec 12 '19 at 9:22
• please not that you're creating a char array `floatString` of size 9. your index 10 is out of bounds! also there are pleny of solutions for your problem online. just enter "hex string to float" into any websearch – Piglet Dec 12 '19 at 9:42
• What exactly are you trying to achieve with all this float to hex conversion? It sounds to me like you are trying to solve a problem and you have a pre-conceived, yet incorrect, notion of how to do it. What is the actual problem you are trying to solve here? – Majenko Dec 12 '19 at 10:44
• Let me edit the question for a better understanding. Sorry for the inappropriate question. – Josh Earnest Dec 12 '19 at 11:06
• I guess you are not talking about hexadecimal data but binary data representing a `double` or float64 in IEEE 754 format. To compare two arrays of 8 bytes for equality, rather use `memcmp` – DataFiddler Dec 12 '19 at 13:01

Comparing floating point values is notoriously difficult. This is because floating point is only an approximation.

You should first define an error margin - a value which is how close together the two values need to be before you consider them to be the same.

For example 1.000000 and 1.000001 could be considered to be the same value in many circumstances.

The simplest method is to just subtract one value from the other, take the absolute value of the result, and see if it is below the error margin.

``````bool almost(float a, float b, float margin) {
float diff = fabs(a - b);
return (diff < margin);
}
``````
• Thanks for the reply – Josh Earnest Dec 12 '19 at 12:08