7

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); 
1

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. You answer provide more help than that of the the duplicate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.