I need to read the binary content of a file and turn the extracted bytes into single precision floating point numbers. How to do this has already been asked here. That question does have proper answers but I'm wondering whether a particular answer is actually valid C++ code.
That answer gives the following code:
float bytesToFloat(uint8_t *bytes, bool big_endian) {
float f;
uint8_t *f_ptr = (uint8_t *) &f;
if (big_endian) {
f_ptr[3] = bytes[0];
f_ptr[2] = bytes[1];
f_ptr[1] = bytes[2];
f_ptr[0] = bytes[3];
} else {
f_ptr[3] = bytes[3];
f_ptr[2] = bytes[2];
f_ptr[1] = bytes[1];
f_ptr[0] = bytes[0];
}
return f;
}
Is this actually valid C++ code? I'm not sure whether it violates any aliasing rules.
Note that I'm targeting platforms with big endian where a float is guaranteed to be at least 32 bits long.