Home > Article > Backend Development > How to Implement a Portable 64-Bit Integer Byte Ordering Function in C ?
Question:
Can we obtain a standard function like htonl that works with 64-bit integers in C , allowing for conversion to network byte order?
Answer:
While there is no explicitly defined function like htonll in the C standard library, it is possible to create a portable implementation. Here are two approaches:
Using Dynamic Endianness Detection:
<code class="cpp">#define htonll(x) ((1 == htonl(1)) ? (x) : ((uint64_t)htonl((x) & 0xFFFFFFFF) << 32) | htonl((x) >> 32)) #define ntohll(x) ((1 == ntohl(1)) ? (x) : ((uint64_t)ntohl((x) & 0xFFFFFFFF) << 32) | ntohl((x) >> 32))</code>
Using Preprocessor Macros:
<code class="cpp">#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>
The above is the detailed content of How to Implement a Portable 64-Bit Integer Byte Ordering Function in C ?. For more information, please follow other related articles on the PHP Chinese website!