Home > Backend Development > C++ > body text

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

Susan Sarandon
Release: 2024-11-02 08:20:02
Original
600 people have browsed it

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

64-bit Endian Conversion in C

The htonl() function is typically used for converting 32-bit integers from host to network byte order. However, this may not be sufficient for 64-bit integers, which require a different approach.

Cross-platform Solution

For a standard cross-platform solution, consider using the htobe64() function. This function is available on Linux and FreeBSD, and can be used as follows:

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

uint64_t host_int = 123;
uint64_t big_endian;

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

Preprocessor Macros

If htobe64() is not available, you can use preprocessor macros to hide platform differences. The following code does this for 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>
Copy after login

Union-based Approach

Another option is to use a union to represent 64-bit integers in both big endian and little endian format. You can then swap the bytes accordingly. However, this approach may break on big endian platforms.

The above is the detailed content of How to Convert 64-bit Integers Between Host and Network Byte Order 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!