This is an implementation of ntohl()
that I wrote as an exercise. ntohl()
takes a uint32_t
value and returns it unchanged if the host architecture is network-byte-order (big-endian), otherwise the value is converted to host-byte-order.
My version converts to little-endian; is it always the case that host-byte-order is taken to mean little-endian? This appears to be the case, from what I have read, but what if the host architecture is middle-endian? Do real implementations of ntohl()
detect other byte-orders, or strictly big- and little-endian?
I am also interested in any comments about the use of a union
to detect endianness on the host machine, suggestions and comparison with other methods, and similarly, comments and suggestions relating to the use of bitwise operators to perform the conversion from big-endian to little-endian.
#ifndef _STDINT_H
#include <stdint.h>
#endif
uint32_t my_ntohl(uint32_t netlong)
{
union {
uint16_t num;
uint8_t bytes[2];
} endian_test = { .bytes = { 0x01, 0x00 }};
if (endian_test.num == 0x0001) {
netlong = (netlong << 24) | ((netlong & 0xFF00ul) << 8) |
((netlong & 0xFF0000ul) >> 8) | (netlong >> 24);
}
return netlong;
}