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

lul*_*yon 5 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);
Run Code Online (Sandbox Code Playgroud)

除了一件事,它们只处理无符号整数(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);
Run Code Online (Sandbox Code Playgroud)

Mas*_*Man 9

从技术上讲,变量内部的值无关紧要,因为您只想借用该功能.将signed转换为unsigned时,其值会发生变化但位数相同.所以将它转换回签名是好的.

编辑:正如amrit所说,它是签名整数网络和主机转换的副本.