c – htons()在Big-Endian系统上做了什么?

前端之家收集整理的这篇文章主要介绍了c – htons()在Big-Endian系统上做了什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

htons()将主机字节顺序转换为网络字节顺序.

网络字节顺序是Big-Endian,主机字节顺序可以是Little-Endian或Big-Endian.

在Little Endian系统上,htons()会将多字节变量的顺序转换为Big-Endian.如果主机字节顺序也是Big-Endian,htons()会做什么?

最佳答案

What will htons() do in case if the host byte order is also big endian?

没什么 – 非常字面.首先介绍htons()的目的是让您编写不关心系统字节序的代码.定义函数的头文件是端点发挥作用的唯一位置.

这是one implementation,用括号围绕其参数表达式替换htons:

#if BYTE_ORDER == BIG_ENDIAN

#define HTONS(n) (n)
#define NTOHS(n) (n)
#define HTONL(n) (n)
#define NTOHL(n) (n)

#else

#define HTONS(n) (((((unsigned short)(n) & 0xFF)) << 8) | (((unsigned short)(n) & 0xFF00) >> 8))
#define NTOHS(n) (((((unsigned short)(n) & 0xFF)) << 8) | (((unsigned short)(n) & 0xFF00) >> 8))

#define HTONL(n) (((((unsigned long)(n) & 0xFF)) << 24) | \
                  ((((unsigned long)(n) & 0xFF00)) << 8) | \
                  ((((unsigned long)(n) & 0xFF0000)) >> 8) | \
                  ((((unsigned long)(n) & 0xFF000000)) >> 24))

#define NTOHL(n) (((((unsigned long)(n) & 0xFF)) << 24) | \
                  ((((unsigned long)(n) & 0xFF00)) << 8) | \
                  ((((unsigned long)(n) & 0xFF0000)) >> 8) | \
                  ((((unsigned long)(n) & 0xFF000000)) >> 24))
#endif

#define htons(n) HTONS(n)
#define ntohs(n) NTOHS(n)

#define htonl(n) HTONL(n)
#define ntohl(n) NTOHL(n)
原文链接:https://www.f2er.com/linux/440203.html

猜你在找的Linux相关文章