What this code attempts to do is to convert a 32-bit representation of a floating-point number into an actual floating-point value. An IEEE 754 binary floating-point value is (most of the time) a representation of a number of the form (−1)s × m × 2e. For a given floating-point format, a certain number of bits within a machine word is allocated for each of s (the sign bit), m (the mantissa or significand bits) and e (the exponent bits). Those bits can be manipulated directly within the bit representation in order to construct any possible floating-point value, bypassing the usual abstractions of ordinary arithmetic operations provided by the language. The converter mentioned in Aryan’s answer is a pretty good way to explore how this works.
Unfortunately, this code is not standard-conforming C++ (or, in fact, C), and that’s thanks to a little something called strict aliasing. In short: if a variable has been declared as being of integer type, it can only be accessed via pointers to that same integer type. Accessing it via a pointer to a different type is not allowed.
A more-or-less officially-sanctioned version would be:
inline static float float_from_bits(std::uint32_t x) {
float result;
static_assert(sizeof(result) == sizeof(x),
"float must be 32 bits wide");
std::memcpy(&result, &x, sizeof(result));
return result;
}
Or, in C++20, simply std::bit_cast<float>(x)
. This is still not quite guaranteed to return expected results by the standard, but at least it doesn’t violate that particular rule.
A direct static_cast
would instead convert the integer into a floating-point value denoting (approximately) the same quantity. This is not a direct bit conversion: performing it entails computing the appropriate values of s, m and e and putting them in the appropriate place according to the number format.