64-Bit Integer Conversion in C : Beyond ntohl()
The htonl() function, as suggested by its documentation, is limited to 32-bit integer conversion. However, in situations where you require 64-bit conversion, there are several options available.
Standard Library Functions
For Linux (glibc >= 2.9) and FreeBSD, the htobe64() function can be used to convert 64-bit integers from big endian to little endian. This function is part of the standard C library.
Union-Based Approach
Alternatively, you can use a union to convert between 64-bit integers and 8-byte character arrays. This approach involves manually swapping the bytes around for big endian platforms.
Preprocessor Macros
To hide platform-specific differences and provide a unified approach, you can use the following preprocessor code:
<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>
This code provides Linux/FreeBSD-style macros on Linux, OpenBSD, FreeBSD, and NetBSD.
Example Usage
To demonstrate the usage of the recommended approach, consider the following code:
<code class="cpp">#include <stdint.h> // For 'uint64_t' int main() { uint64_t host_int = 123; uint64_t big_endian; big_endian = htobe64(host_int); host_int = be64toh(big_endian); return 0; }</code>
This code converts a 64-bit integer, host_int, from little endian to big endian and back, effectively preserving its value.
The above is the detailed content of How to Convert 64-Bit Integers in C Beyond ntohl()?. For more information, please follow other related articles on the PHP Chinese website!