htons() | Host to Network Short |
htonl() | Host to Network Long |
ntohl() | Network to Host Long |
ntohs() | Network to Host Short |
When handling binary data transmitted or shared across platforms, you need be concerned with how each platform stores numerical values. A platform stores values either in big-endian or little-endian format. On big-endian machines, such as PowerPC machines, values are stored with the most-significant bytes first in memory; on little-endian machines, such as Pentium machines, values are stored with the least-significant bytes first. A multibyte value transmitted to a platform with a different format will be misinterpreted if it is not converted properly by one of the computers.
#include <sys/_endian.h>
#define ntohs(x) __DARWIN_OSSwapInt16(x) #define htons(x) __DARWIN_OSSwapInt16(x) #define ntohl(x) __DARWIN_OSSwapInt32(x) #define htonl(x) __DARWIN_OSSwapInt32(x)
CFSwapInt32() & CFSwapInt16()
CFSwapInt32()
instead of
ntonl() and ntohl()
and
CFSwapInt16()
instead of
ntons() and ntohs()
bigEndian & littleEndian
UInt32.bigEndian
UInt32.littleEndian
Example:
Calculate host number by netmask
UInt32.bigEndian
, UInt32.littleEndian
, and UInt32.byteSwapped
seem much nicer than using CFSwapInt32HostToBig
Reference:How do I set integer endianness using htonl in Swift?