Home >Backend Development >C++ >How to Convert 64-bit Integers to Network Byte Order in C ?
Introduction:
Many network protocols require storing 64-bit integers in "network byte order." This differs from the host byte order, potentially causing compatibility issues. Fortunately, for 32-bit integers, the htonl function is widely used for converting to network byte order. Developers often seek an analogous function for 64-bit integers. This article explores the availability of such a function and provides an implementation if not available.
Existence of a Standard Function:
Unfortunately, there is no standard htonll function in the C standard library or any widely adopted portable library.
Implementation:
In the absence of a standard function, we can implement our own portable version. Here are two approaches:
1. Runtime Byte-Swapping:
This approach determines if byte-swapping is necessary by checking the endianness at runtime using htonl(1). If byte-swapping is needed, we swap the 32-bit halves of the 64-bit integer using htonl. The code for this approach is:
<code class="c++">#define htonll(x) ((1==htonl(1)) ? (x) : ((uint64_t)htonl((x) & 0xFFFFFFFF) << 32) | htonl((x) >> 32))</code>
2. Compile-Time Byte-Swapping:
If you have access to a compiler that defines preprocessor macros like __BIG_ENDIAN__, you can use them to optimize the byte-swapping process at compile time. Here's an example:
<code class="c++">#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>
Conclusion:
In conclusion, there is no standard htonll function in C . However, we have provided portable implementations that determine endianness at runtime or compile-time, allowing for the conversion of 64-bit integers to network byte order.
The above is the detailed content of How to Convert 64-bit Integers to Network Byte Order in C ?. For more information, please follow other related articles on the PHP Chinese website!