Alex Rivera | Logout

Signed Integer Network and Host Conversion

Asked 2011-02-02T19:12:53.133
9

I would like to convert a int32_t from host byte order to network byte order and vice versa. I know about the htonl() function and its variants, but this takes unsigned integers. Is there a standard library function which can do the same with signed integers or do I have to implement it myself? And if I have to implement it myself, how should I do it?

I'm looking to find a routine that will work on Linux and Mac OS X.

Edit
Report

1 Answer

2

If one system (you never know what might be running Linux) can potentially use a different representations for negative integers (e.g. one's complement, sign-magnitude; rare, but possible), then transmit numbers as strings and parse them into ints on the receiver. Not as efficient, but unless you're transmitting a large amount of numbers, it won't matter much. If there are many numbers to transmit, you can use some form of compression.

Alternatively, define your own network representation for negative numbers and write your own ntohsl and htonsl.

In either approach, there will be one number on each system that can't be represented on the other; you'll need to decide what the appropriate course of action is when receiving this number.

answered 2011-12-03T19:33:41.493

Your Answer