I'm currently writing a binary application protocol in C that sends uint32_t and doubles across the network using sockets. When writing uint32_t's, I always use the htonl() functions to convert the host byte order to network byte order. However, such a function does not exist for doubles. So I ended up writing a new function which checks the host endianness and reverses the byte order of the double if necessary.
double netHostToNetFloat64(double input)
{
typedef union DoubleData
{
double d;
char c[8];
} DoubleData;
DoubleData input_data, output_data;
if(netHostIsBigEndian())
{
return input;
}
else
{
input_data.d = input;
output_data.c[0] = input_data.c[7];
output_data.c[1] = input_data.c[6];
output_data.c[2] = input_data.c[5];
output_data.c[3] = input_data.c[4];
output_data.c[4] = input_data.c[3];
output_data.c[5] = input_data.c[2];
output_data.c[6] = input_data.c[1];
output_data.c[7] = input_data.c[0];
return output_data.d;
}
}
However, I'm getting some weird results when the network peer reads the double. I'm confident that my function is reversing the byte order, however, I'm curious if storing an invalid double value (i.e. it results in an Inf or NaN) corrupts the output the next time it is read?
Also, I realize that reversing the byte order and placing the result back into a double is stupid, however, I wanted to keep it consistent with the htonl/htons/ntohl/ntohs functions.