64-Bit Integer Conversion from Big Endian to Little Endian in C
The standard C function ntohl() converts 32-bit integers from network byte order (big-endian) to host byte order (little-endian) and vice versa. However, there is a need to convert 64-bit integers (specifically unsigned long long values) on some platforms.
Unfortunately, the C standard does not provide a dedicated function for 64-bit integer conversion. However, platform-specific implementations exist.
Platform-Specific Solutions
Code Example
The following code can be used to convert 64-bit integers on various platforms:
<code class="cpp">#include <stdint.h> // For 'uint64_t' #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 int main() { uint64_t host_int = 123; uint64_t big_endian; // Convert to big-endian big_endian = htobe64(host_int); // Convert back to host byte order host_int = be64toh(big_endian); return 0; }</code>
This example will perform 64-bit integer conversion on Linux, FreeBSD, and OpenBSD using the appropriate platform-specific functions.
The above is the detailed content of How to Convert 64-Bit Integers from Big Endian to Little Endian in C ?. For more information, please follow other related articles on the PHP Chinese website!