I want to send two int64_t
over UDP. To do this I store them in a four-element array, where:
int64_t
int64_t
int64_t
int64_t
My code for sending:
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 */
My code for combining int32_t
back to int64_t
after receiving data
via UDP:
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);
The first number (from
) is always correct. However, what I get from the second printf
is incorrect. What's more, it seems to be dependent on the first number. Example:
Sending:
from
= 125,to
= 20.Received:
from
= 125,to
= 125.Sending:
from
= 1252,to
= 20.Received:
from
= 1252,to
= 1268.What am I doing wrong? Is it the problem of conversion or sending over the network?
There's a typo in your receiver code:
to = from | (int64_t) ntohl(data[2]);
should be
to = to | (int64_t) ntohl(data[2]);