什么时候htonl(x)!= ntohl(x)? (或者当在同一台计算机上与网络字节顺序相互转换时?) [英] When is htonl(x) != ntohl(x) ? (Or when is converting to and from Network Byte Order not equivalent on the same machine?)

查看:95
本文介绍了什么时候htonl(x)!= ntohl(x)? (或者当在同一台计算机上与网络字节顺序相互转换时?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 htonl ntohl

 htonl(x) == ntohl(x);

 htonl(ntohl(x)) == htonl(htonl(x));

换句话说,这两个操作何时在同一台计算机上不相同 >?我能想到的唯一情况是,一台机器不能以2的补数表示整数。

In other words, when are these two operations not equivalent on the same machine? The only scenario I can think of is a machine that does not work on 2's complement for representing integers.

这在很大程度上是出于历史原因,出于编码清晰度或其他原因的原因

Is the reason largely historical, for coding clarity, or for something else?

当今是否存在任何现代架构或环境,它们在同一台机器上在网络字节顺序之间来回转换不是同一代码?

Do any modern architectures or environments exists today where these converting to and from network byte order on the same machine is not the same code in either direction?

推荐答案

我找不到Posix规范的原始草案,但是最近的一个在网上找到有提示。

I couldn't find the original draft of the Posix spec, but a recent one found online has a hint.


网络字节顺序可能不方便处理实际值。
为此,将值存储为普通的
整数更为明智。这就是所谓的主机字节顺序。按照主机字节顺序:

Network byte order may not be convenient for processing actual values. For this, it is more sensible for values to be stored as ordinary integers. This is known as ‘‘host byte order ’’. In host byte order:

The most significant bit might not be stored in the first byte in address order.

**Bits might not be allocated to bytes in any obvious order at all.**

存储在uint8_t对象中的8位值不需要
转换为主机字节顺序或从主机字节顺序转换,因为它们具有相同的
表示形式。可以使用
的htonl(),htons(),ntohl()和ntohs()函数转换16位和32位值。

8-bit values stored in uint8_t objects do not require conversion to or from host byte order, as they have the same representation. 16 and 32-bit values can be converted using the htonl(), htons(), ntohl(),and ntohs() functions.

有趣的是,以下语句是在

Interesting though is the the following statement is made under the discussion of


POSIX标准明确要求8位字符

The POSIX standard explicitly requires 8-bit char and two’s-complement arithmetic.

所以基本上排除了我对1的补码机实现的想法。

So that basically rules out my idea of a 1's complement machine implementation.

但是根本没有任何明显的顺序的说法基本上表明posix委员会至少考虑了 posix / unix在大端或小端上运行的可能性。因此不能排除将htonl和ntohl声明为differnet实现。

But the "any obvious order at all" statement basically suggests that the posix committee at least considered the possibility of posix/unix running on something other than big or little endian. As such declaring htonl and ntohl as differnet implementations can't be ruled out.

因此,简短的回答是 htonl和ntohl是相同的实现,但是两个接口不同的功能是为了将来与未知物兼容。

So the short answer is "htonl and ntohl are the same implementation, but the interface of two different functions is for future compatibility with the unknown."

这篇关于什么时候htonl(x)!= ntohl(x)? (或者当在同一台计算机上与网络字节顺序相互转换时?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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