Recently, I got into a small argument about an efficient code in converting big-endian data to little-endian. I was using `ntohl' library call and the argument against it was to use left shift and sum operation.
//Use ntohl
void *readUint32(void *ptr, uint32_t *value)
{
uint32_t *uint_ptr = (uint32_t *)ptr;
*value = (uint32_t)ntohl( *ptr );
ptr += sizeof(uint32_t);
return ptr;
}
//Use left shift
unsigned char *readUint32ByShift(unsigned char *p,unsigned int *n)
{
unsigned int v = 0;
v <<= 8; v += *p++;
v <<= 8; v += *p++;
v <<= 8; v += *p++;
v <<= 8; v += *p++;
*n = v;
return p;
}
This is with the implementation of a streaming market data with responses in network-byte (big-endian) order. Since it is time critical market data, the application should be faster in parsing and dispatching the data to end client.
The argument was that using `ntohl' was unnecessary, since the code is always going to run in x86 machine (little-endian) and will be faster than the library call implementation. Well, at that time, I didn't know how `ntohl' is implemented, and neither did I know if a left-shift will be faster than the library call. I did a benchmark and found that the library call implementation was twice as fast as the left-shift implementation.
Well, I got my answer.