If I want to transport a signed long (32 bit integer) across the network what do I do? If I send as a signed long then at other end I won't know (potentially) how remote machine represents signed numbers? So what do I do?
-
Tell them how to interpret it. – Thomas Eding Dec 03 '11 at 19:11
-
possible duplicate of [Signed Integer Network and Host Conversion](http://stackoverflow.com/questions/4878781/signed-integer-network-and-host-conversion) – outis Dec 03 '11 at 19:27
3 Answers
Just use ntohl
and htonl
and cast or implicitly convert back and forth between uint32_t
and int32_t
.

- 208,859
- 35
- 376
- 711
Because ntohl()
operates on byte-order, so it doesn't care much about the sign, all it cares for is how many bits are there. To answer the question in title.
To answer the question "what do I do?" beyond stating that you're asking question — you convert it to unsigned and then convert back on the other sign, because besides not knowing whether it's signed or not, the arbitrary remote also doesn't know what this number is about and your particular remote may be more knowledgeable of the matter.

- 138,757
- 24
- 193
- 173
-
OK so I am thinking I can just send as is as long as I mark it as signed then at other end I will do what is necessary to convert back. – Angus Comber Dec 03 '11 at 19:14
-
If the compiler insist, you can cast it to `unit32_t` before doing `htonl` and cas back to signed upon processing through `ntohl`. – Michael Krelin - hacker Dec 03 '11 at 19:16
If the two systems use different representations for negative integers (e.g. two's complement, sign-magnitude), 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.

- 75,655
- 22
- 151
- 221
-
1According to POSIX, integer types `intN_t` must be two's-complement. The `ntohl` function is part of POSIX. – Dietrich Epp Dec 03 '11 at 21:02
-
1@DietrichEpp: ISO C also requires them to be twos complement, and for the most-negative value to be valid (not a trap). – R.. GitHub STOP HELPING ICE Dec 03 '11 at 21:53
-
Converting integers to strings and back again sounds like a very inefficient way forward. – Angus Comber Dec 04 '11 at 21:19