Error converting string of hex floating point [duplicate]

5 days ago 9
ARTICLE AD BOX

Your expectation is wrong. The hex value provided by the Convertor is not the hex representation of the value of the float. It is actually the hex representation of the bytes of the float variable holding the value.

So, you will need to first read the hex value into the memory of a float variable, and then read the value from the variable, eg:

int32_t i = std::stol(fp_as_hex_string.c_str(), nullptr, 0); const float actual_fp = *(float*)&i; // or: // const float actual_fp; // memcpy(&actual_fp, &i, sizeof(actual_fp)); // or: // const float actual_fp = std::bit_cast<float>(i); std::cout << "Floating point converted from hex string: " << actual_fp << "\n";

Output:

Expected floating point from standard format: -0.0327366 Expected value as Hex IEEE-754 format: 0xbea78f5d Floating point converted from hex string: -0.327266

Online Demo

Read Entire Article