Home  >  Article  >  Backend Development  >  How to Convert 64-bit Values Between Network and Host Byte Order in C ?

How to Convert 64-bit Values Between Network and Host Byte Order in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 04:42:30742browse

How to Convert 64-bit Values Between Network and Host Byte Order in C  ?

ntohl() Extension for 64-bit Values

The C function ntohl() is typically used for converting 32-bit values from network byte order to host byte order. However, in certain scenarios, one might require a similar operation for 64-bit values.

Solution

The man pages for htonl() indicate its limitation to 32-bit values, as unsigned long on certain platforms is 32 bits in size. To address the need for 64-bit conversion, several approaches can be explored:

Standard Library:

  • htobe64() and be64toh(): These functions are available on Linux (glibc >= 2.9) and FreeBSD for converting 64-bit values between big endian and little endian.

Implementation Suggestions:

  • Union with unsigned long long and char[8]: A union can be used to manually swap bytes if the platform is not big endian. However, this method is not recommended as it relies on system-dependent assumptions.

Preprocessor Magic:

  • Platform-specific headers: The following preprocessor code allows for portability across different platforms, including Linux, FreeBSD, and OpenBSD:
<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>

Usage Example:

Using the preprocessor magic, the conversion can be performed using the following code snippet:

<code class="cpp">  #include <stdint.h>

  uint64_t  host_int = 123;
  uint64_t  big_endian;

  big_endian = htobe64( host_int );
  host_int = be64toh( big_endian );</code>

This approach provides a standard C library-like interface that is compatible across multiple platforms.

The above is the detailed content of How to Convert 64-bit Values Between Network and Host Byte Order in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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