Recently, I have been integrating another API, in which data transmission is in binary format, and as usual, the format is big-endian. Sounds familiar!!
Generally, in C, you have functions ntohl, ntohs, for converting long integer and short integer values from big-endian to the format of host machine. And obviously, they are more portable way of handling the conversion, rather that your test and shift method of conversion.
Now this time, I had to deal with some 64-bit data and was wondering if there were any functions, and I found the manual pages for endian. This was cool. A week later, I was ready to deploy for testing and got stuck with the problem of the function be64toh not being defined.
The problem was my development environment used g++ 4.4.1 and the test environment used g++ 4.3.2. Ohh god!!! What now? I tried searching for equivalent ones, and found some macros in /usr/include/byteswap.h.
So, now I modified my C++ code to look like this:
double readDouble(void * & data)
{
uint64_t *ptr = (uint64_t *)data;
#if ( (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) && \
(__GNUC_PATCHLEVEL__ > 2) )
uint64_t value = be64toh( *ptr );
#elif __BYTE_ORDER == __LITTLE_ENDIAN
uint64_t value = bswap_64( *ptr );
#else
uint64_t value = *ptr;
#endif
ptr++;
data = ptr;
double *dptr = (double *)&value;
return *dptr;
}
Code is now deployed for testing. :-)