gpt4 book ai didi

对 htonl 输出感到困惑

转载 作者:太空宇宙 更新时间:2023-11-04 07:20:51 24 4
gpt4 key购买 nike

我有一个简单的问题。这段代码:

   int t = 1;

int y = htonl(t);
printf("Y = %d, sizeof(int)=%d", y, sizeof(int));

打印

Y = 16777216, sizeof(int)=4

在小端机器上(实际上是在线编译器)。

我期望 y 是数字(二进制​​):1000....000(0 - 31 次)。

但是 16777216 在 1 旁边只有大约 25 个零(二进制)。

我错过了什么?

最佳答案

int t = 1;

在内存中(对于4字节系统)是这样呈现的

 ---------------
| 0 | 0 | 0 | 1 |
---------------
^ ^
| byte | = 0x1 = 00000001 in binary

二进制格式为

00000000 00000000 00000000 00000001 

htonl() 如果您的系统是小端系统,则允许反转字节

所以 htonl(t) 将返回:

 ---------------
| 1 | 0 | 0 | 0 |
---------------
^
| = 0x1 = 00000001 in binary

所以二进制的整个htonl(t)

00000001 00000000 00000000 00000000

等于十进制的16777216

关于对 htonl 输出感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21730405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com