Searching for a "Standard" 64-Bit htonl Function in C
In C , the htonl function is used to convert a 32-bit integer from host byte order to network byte order. However, for 64-bit integers, there is currently no "standard" htonll function available in the language.
Portable Implementation of htonll
To address this need, programmers have devised portable implementations of htonll to handle 64-bit integer byte order conversion across different platforms, including Windows, Linux, and AIX. One such implementation is:
<code class="cpp">#define htonll(x) ((1==htonl(1)) ? (x) : ((uint64_t)htonl((x) & 0xFFFFFFFF) << 32) | htonl((x) >> 32)) #define ntohll(x) ((1==ntohl(1)) ? (x) : ((uint64_t)ntohl((x) & 0xFFFFFFFF) << 32) | ntohl((x) >> 32))</code>
This implementation uses the htonl function for the 32-bit conversion and applies it twice, once for each 32-bit half of the 64-bit integer, while also ensuring the swapped parts are in the correct order.
Determining Endianness
As C lacks a portable way to determine endianness at compile-time, the implementation above checks it at runtime by calling htonl on the integer 1. If the result equals 1, the system is little-endian, and no byte swapping is necessary. Otherwise, it is big-endian, and the implementation swaps the bytes.
Alternative Using Compiler Directives
Another portable implementation uses compiler directives to differentiate between big-endian and little-endian architectures:
<code class="cpp">#if __BIG_ENDIAN__ # define htonll(x) (x) # define ntohll(x) (x) #else # define htonll(x) (((uint64_t)htonl((x) & 0xFFFFFFFF) << 32) | htonl((x) >> 32)) # define ntohll(x) (((uint64_t)ntohl((x) & 0xFFFFFFFF) << 32) | ntohl((x) >> 32)) #endif</code>
This implementation defines htonll and ntohll functions based on the BIG_ENDIAN directive, which is supported by most compilers and operating systems.
The above is the detailed content of How to Implement a 64-Bit htonll Function in C ?. For more information, please follow other related articles on the PHP Chinese website!