如何将int64_t分成两个int32_t并通过网络发送?

pmi*_*hna 1 c unix posix udp int64

我想int64_t通过UDP 发送两个.为此,我将它们存储在一个四元素数组中,其中:

  • [0] - 低于第一个的32 int64_t
  • [1] - 第一个高32位 int64_t
  • [2] - 第二个的低32位 int64_t
  • [3] - 如果是第二个,则高32位 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 */
Run Code Online (Sandbox Code Playgroud)

我通过UDP 接收后组合int32_t回来的代码:int64_tdata

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);
Run Code Online (Sandbox Code Playgroud)

第一个数字(from)始终是正确的.但是,我从第二个得到的printf是不正确的.更重要的是,它似乎取决于第一个数字.例:

发送:

  • from = 125,
  • to = 20.

收稿日期:

  • from = 125,
  • to = 125.

发送:

  • from = 1252,
  • to = 20.

收稿日期:

  • from = 1252,
  • to = 1268.

我究竟做错了什么?这是转换或通过网络发送的问题吗?

sim*_*onc 6

您的接收器代码中有一个拼写错误:

to = from | (int64_t) ntohl(data[2]);
Run Code Online (Sandbox Code Playgroud)

应该

to = to | (int64_t) ntohl(data[2]);
Run Code Online (Sandbox Code Playgroud)

  • +1.这就是为什么重复代码(或复制粘贴)很糟糕,你应该将这种东西放入方法/宏 - 一旦大脑关闭,你的手指开始输入垃圾. (4认同)