我必须从 udp 客户端发送一个包到 udp 服务器(我做的)但问题是这个声明不起作用
#define RRQ 1
.
.
.
uint16_t op = htons(RRQ);
我也试过
uint16_t op = htons(1);
和
int k = 1;
uint16_t op = htons(k);
但这并没有把 1 放在 op 而是 256
我尝试将这个包发送到服务器,我收到了包,并且在服务器端得到了相同的结果(我发现 op == 256 而不是 op == 1,就像它应该的那样) 感谢阅读!
最佳答案
Why this uint16_t variable declaration doesn't work?
嗯,它确实...
您可能在一台小端机器上,所以结果是正确的。
在小端机器上,内存是这样的:
uint16_t v1 = 1; --> Memory: 0x01 0x00
uint16_t v256 = 256; --> Memory: 0x00 0x01
按网络顺序是这样的:
uint16_t v1 = 1; --> Memory: 0x00 0x01
uint16_t v256 = 256; --> Memory: 0x01 0x00
因此 k
的值为 1
,在内存中为 0x01 0x00
然后 op
将被分配 k
转换为网络顺序,因此在内存中它将是 0x00 0x01
。
当您在主机上将其打印为 uint16_t
时,您将看到结果 256。
这个小程序说明了正在发生的事情:
#include <stdio.h>
#include <inttypes.h>
#include <arpa/inet.h>
int main()
{
uint16_t k = 1;
unsigned char* p = (unsigned char*)&k;
printf("k=%hd\n", k);
for (size_t i = 0; i<sizeof k; ++i)
{
printf("%02X\n", *p++);
}
uint16_t op = htons(k);
unsigned char* pop = (unsigned char*)&op;
printf("op=%hd\n", op);
for (size_t i = 0; i<sizeof op; ++i)
{
printf("%02X\n", *pop++);
}
return 0;
}
输出:
k=1
01
00
op=256
00
01
关于c - 为什么这个 uint16_t 变量声明不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58068242/