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.

1
  • What does that mean - what are you hoping to do with the signed bit that wouldn't happen in you just used the unsigned function and casts? Commented Feb 2, 2011 at 19:14

3 Answers 3

7

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.

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

3 Comments

Since he is using C, he should probably just call htonl((uint32_t)address);
@joeforker that will lead to undefined behaviour in case of overflow. please delete your comment. use memcpy instead.
It works, it only swaps four bytes. No overflow. OTOH memcpy() leaves the bytes in the same order.
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.

Comments

0

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 

1 Comment

ntoh is not an unconditional byte swap (it is no-op on big endian systems), and the proposed builtins take unsigned integers whereas the question is about signed integers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.