Signed Integer Network and Host Conversion

本小妞迷上赌 提交于 2019-12-29 06:17:35

问题


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:


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.




回答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.




回答3:


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


来源:https://stackoverflow.com/questions/4878781/signed-integer-network-and-host-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!