I have a problem translate byte order between host(CPU dependent) and network(big endian). These are all the APIs(in "arpa/inet.h" for Linux) I've found that might solve my problem.
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
Except for one thing, they only handle unsigned integer(2 bytes or 4 byte).
So is there any approach to handle signed integer case? In other words, how to implement the following functions(APIs)?
int32_t htonl(int32_t hostlong);
int16_t htons(int16_t hostshort);
int32_t ntohl(int32_t netlong);
int16_t ntohs(int16_t netshort);
The htonl() function is used to convert a long (4-byte) integer from the local host byte order to standard network byte order.
The htons() function converts the unsigned short integer hostshort from host byte order to network byte order. The ntohl() function converts the unsigned integer netlong from network byte order to host byte order.
The htonl() and htons() functions shall return the argument value converted from host to network byte order. The ntohl() and ntohs() functions shall return the argument value converted from network to host byte order.
The ntohs() function translates a short integer from network byte order to host byte order. Parameter Description a. The unsigned short integer to be put into host byte order. in_port_t netshort. Is typed to the unsigned short integer to be put into host byte order.
Technically speaking, it doesn't matter what the value is inside the variable since you just want to borrow the functionality. When assigning a signed to an unsigned, its value changes but the bits are the same. So converting it back to signed is alright.
Edit: As amrit said, it is a duplicate of Signed Integer Network and Host Conversion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With