c - 有符号整数的字节顺序转换

标签 c endianness

我在主机(依赖于 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/

相关文章:

c - 如何使用 syslog-ng 仅登录 **mylog**,而不是 **mylog** 和 **syslog**?

c - 向线程发送消息是什么意思?

c - 什么是字节?

c - 为什么我的函数中的 count 变量不增加?

c - 使用 ntohs 的无符号整数

c - 如何检查 C 中的地址是否有效或已分配?

go - 将 big.Int 转换为 little-endian 字节 slice

c# - 如何模拟 BitConverter.IsLittleEndian 与我的单元测试相反的环境?

Java readInt 方法返回 Scala 中 Int 的 LittleEndian 而不是 BigEndian 值

将 uint64_t 转换为 FILETIME