I\'ve recently been working on a system that needs to store and load large quantities of data, including single-precision floating-point values. I decided to standardise on
Much simpler, and depending on the same assumption as yours (which is that float and integer types have the same byte order, and is almost universally valid -- realistically you'll never encounter a system where it isn't true):
#include
float htonf(float val) {
uint32_t rep;
memcpy(&rep, &val, sizeof rep);
rep = htonl(rep);
memcpy(&val, &rep, sizeof rep);
return val;
}
Any reasonably good compiler will optimize away the two memcpy calls; they are present to defeat over-eager strict aliasing optimizations, so this ends up being as efficient as htonl plus the overhead of a single function call.