Signed Integer Network and Host Conversion
Asked Answered
P

3

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.

Preside answered 2/2, 2011 at 19:12 Comment(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?Aldridge
M
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.

Maite answered 2/2, 2011 at 19:15 Comment(3)
Since he is using C, he should probably just call htonl((uint32_t)address);Donte
@Donte that will lead to undefined behaviour in case of overflow. please delete your comment. use memcpy instead.Durst
It works, it only swaps four bytes. No overflow. OTOH memcpy() leaves the bytes in the same order.Donte
A
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.

Achieve answered 3/12, 2011 at 19:33 Comment(0)
D
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
Donte answered 18/8, 2016 at 1:56 Comment(1)
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.Brocket

© 2022 - 2024 — McMap. All rights reserved.