When converting network data between big and little endian, it's my understanding that we swap all the bytes that make up the type. Regardless of the type's size, we swap them so that the first byte becomes the last byte, and the last byte becomes the first byte.
This can be expressed generically with the function below:
void SwapBytes(void *pv, size_t n)
{
char *p = pv;
size_t lo, hi;
for(lo=0, hi=n-1; hi>lo; lo++, hi--)
{
char tmp=p[lo];
p[lo] = p[hi];
p[hi] = tmp;
}
}
Without concern for efficiency,
I had hoped this would work on any data type-- including IEEE 754 doubles.
Then, I came across the following post,
where the user has swapped the bytes of a double in 4 byte chunks:
void send_double(double d) {
long int i64 = *((reinterpret_cast<int *>)(&d)); /* Ugly, but works */
int hiword = htonl(static_cast<int>(i64 >> 32));
send(hiword);
int loword = htonl(static_cast<int>(i64));
send(loword);
}
double recv_double() {
int hiword = ntohl(recv_int());
int loword = ntohl(recv_int());
long int i64 = (((static_cast<long int>) hiword) << 32) | loword;
return *((reinterpret_cast<double *>(&i64));
}
Is there a special rule about this when it comes to network byte order?
At first, I thought it was about swapping 4 bytes at a time, regardless of the type, but that wouldn't make sense for uint16, where there are only 2 bytes.
What is the correct way to convert a IEEE 754 double into network byte order?
Do I flip all 8 bytes, or do I flip each half individually?