Signed Integer Network and Host Conversion Signed Integer Network and Host Conversion unix unix

Signed Integer Network and Host Conversion


It does not matter. htonl is concerned with bytes, not with arithmetical value of the number. Use reinterpret_cast to change the number to unsigned and back again, if you have to.


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.


If you are using gcc it has a set of builtins for this purpose. They usually compile down to a single instruction.

uint16_t __builtin_bswap16 (uint16_t x);uint32_t __builtin_bswap32 (uint32_t x);uint64_t __builtin_bswap64 (uint64_t x);

On my machine, __builtin_bswap32() compiled to

bswap   %eax