Home  >  Article  >  Backend Development  >  How to Convert 64-Bit Integers from Big Endian to Little Endian in C ?

How to Convert 64-Bit Integers from Big Endian to Little Endian in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 07:51:02892browse

How to Convert 64-Bit Integers from Big Endian to Little Endian in C  ?

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

  • Linux and FreeBSD: htobe64 and be64toh are defined in for 64-bit integer conversion.
  • OpenBSD: Custom macros be16toh, be32toh, and be64toh are available in for byte order conversion.

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!

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