Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-10-30 07:51:02
Original
903 people have browsed it

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>
Copy after login

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!

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!