Home > Backend Development > C++ > body text

How to Convert 64-Bit Integers in C Beyond ntohl()?

Barbara Streisand
Release: 2024-10-30 11:27:27
Original
405 people have browsed it

How to Convert 64-Bit Integers in C   Beyond ntohl()?

64-Bit Integer Conversion in C : Beyond ntohl()

The htonl() function, as suggested by its documentation, is limited to 32-bit integer conversion. However, in situations where you require 64-bit conversion, there are several options available.

Standard Library Functions

For Linux (glibc >= 2.9) and FreeBSD, the htobe64() function can be used to convert 64-bit integers from big endian to little endian. This function is part of the standard C library.

Union-Based Approach

Alternatively, you can use a union to convert between 64-bit integers and 8-byte character arrays. This approach involves manually swapping the bytes around for big endian platforms.

Preprocessor Macros

To hide platform-specific differences and provide a unified approach, you can use the following preprocessor code:

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

This code provides Linux/FreeBSD-style macros on Linux, OpenBSD, FreeBSD, and NetBSD.

Example Usage

To demonstrate the usage of the recommended approach, consider the following code:

<code class="cpp">#include <stdint.h>    // For 'uint64_t'

int main() {
  uint64_t host_int = 123;
  uint64_t big_endian;

  big_endian = htobe64(host_int);
  host_int = be64toh(big_endian);

  return 0;
}</code>
Copy after login

This code converts a 64-bit integer, host_int, from little endian to big endian and back, effectively preserving its value.

The above is the detailed content of How to Convert 64-Bit Integers in C Beyond ntohl()?. 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!