0

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).

I have managed to do the conversion of hexadecimal to float. Can someone please help me in comparing the two float values?

6
  • 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
    Commented Dec 12, 2019 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
    Commented Dec 12, 2019 at 9:42
  • 1
    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
    Commented Dec 12, 2019 at 10:44
  • Let me edit the question for a better understanding. Sorry for the inappropriate question. Commented Dec 12, 2019 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 Commented Dec 12, 2019 at 13:01

1 Answer 1

1

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);
}
1
  • Thanks for the reply Commented Dec 12, 2019 at 12:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.