C++ 中的 64 位 ntohl()? [英] 64 bit ntohl() in C++?

查看:41
本文介绍了C++ 中的 64 位 ntohl()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

htonl() 的手册页似乎建议您最多只能将其用于 32 位值.(实际上,ntohl() 是为 unsigned long 定义的,在我的平台上是 32 位.我想如果 unsigned long 是 8 个字节,它可以用于 64 位整数).

The man pages for htonl() seem to suggest that you can only use it for up to 32 bit values. (In reality, ntohl() is defined for unsigned long, which on my platform is 32 bits. I suppose if the unsigned long were 8 bytes, it would work for 64 bit ints).

我的问题是我需要将 64 位整数(在我的例子中,这是一个 unsigned long long)从 big endian 转换为 little endian.现在,我需要进行特定的转换.但如果目标平台是大端的,如果函数(如 ntohl())不会转换我的 64 位值,那就更好了.(我宁愿避免添加我自己的预处理器魔法来做到这一点).

My problem is that I need to convert 64 bit integers (in my case, this is an unsigned long long) from big endian to little endian. Right now, I need to do that specific conversion. But it would be even nicer if the function (like ntohl()) would NOT convert my 64 bit value if the target platform WAS big endian. (I'd rather avoid adding my own preprocessor magic to do this).

我可以使用什么?我想要一些标准的东西,如果它存在的话,但我愿意接受实施建议.我曾经见过使用联合完成的这种类型的转换.我想我可以有一个带有 unsigned long long 和 char[8] 的联合.然后相应地交换字节.(显然会在大端平台上中断).

What can I use? I would like something that is standard if it exists, but I am open to implementation suggestions. I have seen this type of conversion done in the past using unions. I suppose I could have a union with an unsigned long long and a char[8]. Then swap the bytes around accordingly. (Obviously would break on platforms that were big endian).

推荐答案

文档:man htobe64 on Linux (glibc >= 2.9) 或 FreeBSD.

Documentation: man htobe64 on Linux (glibc >= 2.9) or FreeBSD.

不幸的是,在 2009 年的一次尝试中,OpenBSD、FreeBSD 和 glibc (Linux) 并没有很顺利地协同工作来为此创建一个(非内核 API)libc 标准.

Unfortunately OpenBSD, FreeBSD and glibc (Linux) did not quite work together smoothly to create one (non-kernel-API) libc standard for this, during an attempt in 2009.

目前,这个简短的预处理器代码:

Currently, this short bit of preprocessor code:

#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

(在 Linux 和 OpenBSD 上测试)应该隐藏差异.它为您提供了这 4 个平台上的 Linux/FreeBSD 风格的宏.

(tested on Linux and OpenBSD) should hide the differences. It gives you the Linux/FreeBSD-style macros on those 4 platforms.

使用示例:

  #include <stdint.h>    // For 'uint64_t'

  uint64_t  host_int = 123;
  uint64_t  big_endian;

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

这是目前可用的最标准的 C 库"式方法.

It's the most "standard C library"-ish approach available at the moment.

这篇关于C++ 中的 64 位 ntohl()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆