ntohl() Extension for 64-bit Values
The C function ntohl() is typically used for converting 32-bit values from network byte order to host byte order. However, in certain scenarios, one might require a similar operation for 64-bit values.
Solution
The man pages for htonl() indicate its limitation to 32-bit values, as unsigned long on certain platforms is 32 bits in size. To address the need for 64-bit conversion, several approaches can be explored:
Standard Library:
Implementation Suggestions:
Preprocessor Magic:
<code class="cpp">#if defined(__linux__) # include <endian.h> #elif defined(__FreeBSD__) || defined(__NetBSD__) # include <sys/endian.h> #elif defined(__OpenBSD__) # include <sys/types.h> # define be16toh(x) betoh16(x) # define be32toh(x) betoh32(x) # define be64toh(x) betoh64(x) #endif</code>
Usage Example:
Using the preprocessor magic, the conversion can be performed using the following code snippet:
<code class="cpp"> #include <stdint.h> uint64_t host_int = 123; uint64_t big_endian; big_endian = htobe64( host_int ); host_int = be64toh( big_endian );</code>
This approach provides a standard C library-like interface that is compatible across multiple platforms.
The above is the detailed content of How to Convert 64-bit Values Between Network and Host Byte Order in C ?. For more information, please follow other related articles on the PHP Chinese website!