我想通过UDP发送两个int64_t
。为此,我将它们存储在一个四元素数组中,其中:
int64_t
int64_t
int64_t
int64_t
我的发送代码:
int64_t from, to;
/* some logic here */
data[0] = htonl((int32_t) from);
data[1] = htonl((int32_t) (from >> 32));
data[2] = htonl((int32_t) to);
data[3] = htonl((int32_t) (to >> 32));
/* sending via UDP here */
我通过UDP接收int32_t
后将int64_t
合并回data
的代码:
int64_t from, to;
from = (int64_t) ntohl(data[1]);
from = (from << 32);
from = from | (int64_t) ntohl(data[0]);
to = (int64_t) ntohl(data[3]);
to = (to << 32);
to = from | (int64_t) ntohl(data[2]);
printf("received from = %" PRId64 "\n", from);
printf("received to = %" PRId64 "\n", to);
第一个数字(from
)始终是正确的。但是,我从第二个printf
得到的是不正确的。更重要的是,它似乎取决于第一个数字。例如:
发送:
from
= 125,to
= 20。收到:
from
= 125,to
= 125。发送:
from
= 1252,to
= 20。收到:
from
= 1252,to
= 1268。我做错了什么?这是转换或通过网络发送的问题吗?
答案 0 :(得分:6)
接收器代码中有拼写错误:
to = from | (int64_t) ntohl(data[2]);
应该是
to = to | (int64_t) ntohl(data[2]);
答案 1 :(得分:2)
请注意,您向后发送64位值。 htonl()
确保int32以正确的顺序发送,但RFC 1700定义该字段的最重要的八位字节将首先发送:
当传输多个八位字节数时,最重要的八位字节是 首先传播。