我在主机(依赖于 CPU)和网络(大端)之间转换字节顺序时遇到问题。这些是我发现的所有 API(在 Linux 的“arpa/inet.h”中)可能会解决我的问题。
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
除了一件事,它们只处理无符号整数(2 字节或 4 字节)。
那么有什么方法可以处理有符号整数的情况吗?换句话说,如何实现以下功能(API)?
int32_t htonl(int32_t hostlong);
int16_t htons(int16_t hostshort);
int32_t ntohl(int32_t netlong);
int16_t ntohs(int16_t netshort);
最佳答案
从技术上讲,变量中的值是什么并不重要,因为您只是想借用功能。将有符号分配给无符号时,其值会发生变化,但位相同。因此,将其转换回签名就可以了。
编辑:正如 amrit 所说,它是 Signed Integer Network and Host Conversion 的副本.
关于c - 有符号整数的字节顺序转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18276527/