Note: I mistakenly asked about static_cast originally; this is why the top answer mentions static_cast at first.
I have some binary files w
In short, it's incorrect. You are casting an integer to a float, and it will be interpreted by the compiler as an integer at the time. The union solution presented above works.
Another way to do the same sort of thing as the union is would be to use this:
return *reinterpret_cast( &val );
It is equally safe/unsafe as the union solution above, and I would definitely recommend an assert to make sure float is the same size as int.
I would also warn that there ARE floating point formats that are not IEEE-754 or IEEE-854 compatible (these two standards have the same format for float numbers, I'm not entirely sure what the detail difference is, to be honest). So, if you have a computer that uses a different floating point format, it would fall over. I'm not sure if there is any way to check that, aside from perhaps having a canned set of bytes stored away somewhere, along with the expected values in float, then convert the values and see if it comes up "right".