I have a function that converts a series of bytes into a floating point number, using an union. I use it to precisely represent some numbers that are hard to write, such as NaN and Infinity.
float i2f(uint32_t i)
{
union { uint32_t i; float f; } u;
u.i = i;
return u.f;
}
The problem I'm having is that I cannot use this function in places that expect a constant expression, such as static initializers:
// error: initializer element is not constant
float fs[2] = { i2f(0xffc00000), i2f(0x7f800000) };
Is there another way to achieve this same effect, such that the resulting expression is valid as a constant expression?
So far, the only way I found to represent a NaN as a constant is using the __builtin_nan extension, which is not portable. I would prefer something that works inside the boundaries of the C standard, if possible.