Home > Article > Backend Development > How to Convert 64-bit Integers Between Host and Network Byte Order in C ?
64-bit Endian Conversion in C
The htonl() function is typically used for converting 32-bit integers from host to network byte order. However, this may not be sufficient for 64-bit integers, which require a different approach.
Cross-platform Solution
For a standard cross-platform solution, consider using the htobe64() function. This function is available on Linux and FreeBSD, and can be used as follows:
<code class="cpp">#include <endian.h> uint64_t host_int = 123; uint64_t big_endian; big_endian = htobe64(host_int); host_int = be64toh(big_endian);</code>
Preprocessor Macros
If htobe64() is not available, you can use preprocessor macros to hide platform differences. The following code does this for Linux, FreeBSD, and OpenBSD:
<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>
Union-based Approach
Another option is to use a union to represent 64-bit integers in both big endian and little endian format. You can then swap the bytes accordingly. However, this approach may break on big endian platforms.
The above is the detailed content of How to Convert 64-bit Integers Between Host and Network Byte Order in C ?. For more information, please follow other related articles on the PHP Chinese website!