Home > Backend Development > C++ > body text

How to Implement a Portable 64-Bit Integer Byte Ordering Function in C ?

Mary-Kate Olsen
Release: 2024-11-01 01:33:28
Original
323 people have browsed it

How to Implement a Portable 64-Bit Integer Byte Ordering Function in C  ?

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>
Copy after login
  • The macro htonll converts a 64-bit integer x to network byte order by swapping 32-bit words if the target architecture is little-endian.
  • ntohll performs the reverse operation, converting from network byte order to native byte order.

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>
Copy after login
  • This approach defines htonll and ntohll using preprocessor macros based on the __BIG_ENDIAN__ or __LITTLE_ENDIAN__ preprocessor symbols provided by most compilers.
  • If the architecture is big-endian (symbol defined), the functions simply return the input value since no byte swapping is needed.
  • For little-endian architectures, the functions perform byte swapping as in the previous example.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!