3

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?

Angus Comber
  • 9,316
  • 14
  • 59
  • 107

3 Answers3

7

Just use ntohl and htonl and cast or implicitly convert back and forth between uint32_t and int32_t.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
2

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.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
1

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.

outis
  • 75,655
  • 22
  • 151
  • 221