x86机器本机是小端序,在endian.h中有定义如下:
/* i386/x86_64 are little-endian. */
#define __BYTE_ORDER __LITTLE_ENDIAN
对于位的翻转操作定义如下:
# if __BYTE_ORDER == __LITTLE_ENDIAN
# define htobe16(x) __bswap_16 (x)
# define htole16(x) (x)
# define be16toh(x) __bswap_16 (x)
# define le16toh(x) (x)
# define htobe32(x) __bswap_32 (x)
# define htole32(x) (x)
# define be32toh(x) __bswap_32 (x)
# define le32toh(x) (x)
# define htobe64(x) __bswap_64 (x)
# define htole64(x) (x)
# define be64toh(x) __bswap_64 (x)
# define le64toh(x) (x)
其中__bswap_32的定义为内联函数:
static __inline unsigned int
__bswap_32 (unsigned int __bsx)
{
return __builtin_bswap32 (__bsx);
}
在__builtin系列函数中,包括1的个数计算,前导0的计算,后导0的计算等系列操作.
__bswap_16的汇编定义如下:
__asm__ ("rorw $8, %w0" \
: "=r" (__v) \
: "0" (__x) \
: "cc"); \
__v; }))
在没有内联函数的操作中,可以通过汇编高效的完成位的翻转.
在webrtc中的使用方法如下:
inline uint32_t HostToNetwork32(uint32_t n) {
return htobe32(n);
}
inline uint32_t NetworkToHost32(uint32_t n) {
return be32toh(n);
}