整数的htonl()和ntohl()的输出相同 [英] Same output for htonl() and ntohl() on an integer
问题描述
我在低字节序[LE]机器[Linux,Intel处理器]上运行了以下程序。我无法在下面的代码片段中解释这3个输出。由于计算机是LE,因此 a
的值存储为 0x78563412
。打印时,它将显示其实际值。由于它是LE机器,所以我希望 ntohl()
是无操作并显示 0x78563412
在做。但是,我希望包含 htonl()
的第二个打印语句的 0x12345678
。
I ran the following program on little-endian [LE] machine [Linux, Intel processor]. I am unable to explain the 3 outputs in below code snippet. Since machine is LE, the value of a
is stored as 0x78563412
. When printing, it is displaying its actual value. Since its an LE machine, I expect ntohl()
to be a no-op and display 0x78563412
, which it is doing. However, I expect 0x12345678
for 2nd print statement containing htonl()
. Can someone please help me understand why they are same?
int main()
{
int a = 0x12345678;
printf("Original - 0x%x\n", (a));
printf("Network - 0x%x\n", htonl(a));
printf("Host - 0x%x\n", ntohl(a));
return 0;
}
输出:
Original - 0x12345678
Network - 0x78563412
Host - 0x78563412
推荐答案
由于它是LE机器,我希望
ntohl()
是一个没有操作
那是错误。网络字节顺序为 big-endian ,主机字节顺序为little-endian。因此, ntohl
和 htonl
均返回其输入的字节交换版本。
That's the mistake. Network byte order is big-endian, host byte order is little-endian. Therefore, both ntohl
and htonl
return a byte-swapped version of their input.
请记住, htonl
的意义在于您可以在主机上取一个整数,然后输入:
Remember, the point of htonl
is that you can take an integer on the host, then write:
int i = htonl(a);
,结果是 i
,当使用网络字节顺序解释时,其值与 a
相同。因此,如果将 i
的对象表示形式写入套接字,并且另一端的阅读器期望网络字节顺序为4字节整数,它将读取的值。 a
。
and the result is that the memory of i
, when interpreted using network byte order, has the same value that a
does. Hence, if you write the object representation of i
to a socket and the reader at the other end expects a 4-byte integer in network byte order, it will read the value of a
.
并显示
0x78563412
这是您要写的吗?如果 ntohl
是无操作(或者说是一个身份函数),那么您的第三行必然会打印出与第一行相同的内容,因为您会得到 ntohl(a)== a
。这就是在big-endian实现中发生的情况,您的程序将在其中打印:
Is this what you intended to write? If ntohl
were a no-op (or rather, an identity function), then your third line necessarily would print the same thing as your first line, because you would have ntohl(a) == a
. This is what happens on big-endian implementations, where your program prints:
Original - 0x12345678
Network - 0x12345678
Host - 0x12345678
这篇关于整数的htonl()和ntohl()的输出相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!