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

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

问题描述

的手册页 htonl()似乎表明,你只能用它长达32位值。 (在现实中, ntohl()被定义为无符号长,我的平台上为32位。我想,如果无符号长为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位整数(对我来说,这是一个无符号很长很长)从大端为小端。现在,我需要做的具体的转换。但它会更好,如果函数(如 ntohl())不会将我的64位值,如果目标平台是大端。 (我宁愿避免增加自己的preprocessor魔法做到这一点)。

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).

推荐答案

文件:男人htobe64 在Linux(glibc的> = 2.9)或FreeBSD

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

不幸的OpenBSD,FreeBSD和glibc的(Linux)的不太共同努力,顺利在2009年试图创建一个(非内核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.

目前,preprocessor ​​code这短短的一点:

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库-ish方法目前可用。

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

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

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