我正在设计自定义网络协议(protocol),我需要发送 uint64_t
变量(表示文件的字节长度)到 socket
在 portable和 POSIX-compliant方式。
不幸的是manual表示宽度为 64 的整数类型不保证存在:
If an implementation provides integer types with width 64 that meet these requirements, then the following types are required:
int64_t
uint64_t
此外,没有符合 POSIX 标准的 htonl
, htons
, ntohl
, ntohs
等价物(注意 bswap_64
is not 符合 POSIX)。
通过套接字发送 64 位变量的最佳做法是什么?
最佳答案
当然,您可以只应用 htonl()
两次:
const uint64_t x = ...
const uint32_t upper_be = htonl(x >> 32);
const uint32_t lower_be = htonl((uint32_t) x);
这将为您提供两个 32 位变量,其中包含 64 位变量 x
的高 32 位和低 32 位的大端版本。
如果你是严格的 POSIX,你不能使用 uint64_t
因为它不能保证存在。然后你可以这样做:
typedef struct {
uint32_t upper;
uint32_t lower;
} my_uint64;
当然,只有 htonl()
直接。
关于c - 通过 POSIX 套接字发送 64 位变量的可移植方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40526279/