This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Not able to convert hex to float using the float_t typecast.Is there a workaround for this?

So for this what I am trying to do is-

result = ((float_t)0x3F4040A3);

NRF_LOG_INFO("My float number" NRF_LOG_FLOAT_MARKER "\r\n", NRF_LOG_FLOAT(result));

But this is giving me result to be as ‭1061175459‬.00 rather than 0.750986.

So for this conversion reference I am using online float to hex converter.

  • Hi,

    Typecasting 0x3F4040A3 (which is an integer) to the type float_t will not treat the binary data from the hexadecimal notation and treat that as if it were a float.

    Converting the data from the integer 0x3F4040A3, which is 1061175459 in decimal, to a float should yield the bytes 0x4e7d0103, which is 1061175488.00 in decimal notation (with small error due to conversion / lack of precision.)

    To add to the confusion, the size of float_t may be bigger than that of float. float_t is implementation specific and may differ from toolchain to toolchain or even from one version of a toolchain to the next. What I am saying is you might want to use float instead of float_t. The fact that you did not seem to lose precision probably means your float_t is not 32 bits (4 bytes) but rather longer than that. You can check the data size (in bytes) for the float_t type with "sizeof(float_t)".

    If you have a constant, defined as a hexadecimal value, that should be treated as a float, if it is known at compile time it is better to convert it manually and store it directly as a float (e.g. "result = 0.750986".)

    If you really need to treat the hexadecimal value as if it were the (binary) representation of a float, then storing it in an int, then casting a pointer to that int from an int pointer to a float pointer, then reading the value pointed to by that float pointer, might be a way to do this. Or, alternatively, use a union of float and int, then store the int and read the float.

    Regards,
    Terje

Related