An implementation of ntohf() with code

I am working on extracting data from some binary navigation messages today. Working with binary data can be difficult and quite confusing – especially when converting byte order from network (big endian) to host byte order (possibly little endian). The integer types are well covered by ntohs() and ntohl() et al. but when dealing with floats things can get a bit harder as ntohf() isn’t always available to the hard pressed programmer!

So I have included a simple implementation below, I have tested it during my own use, but it use at your own risk as this code may well be an example of a rather dubious use of unions!

//
#include 

#ifndef ntohf

// Converts a 32 bit IEEE float represented as
// 4 bytes in network byte order to a float in host byte order
// the 4 bytes are passed as an unsigned 32bit integer
inline float ntohf(uint32_t net32)
{
    union {
        float f;
        uint32_t u;
    } value;

    // Swap bytes if necessary and store to value
    value.u = ntohl(net32);

    // return value as float
    return value.f;
}

#endif
//

This version is slightly adapted from an original implementation by Kevin Bowling (pls. see copyright notice).