C:判断主机字节序(大端BE小端LE)
通过简单的C程序可以判断当前主机字节序是大端(Big-Endian:BE)或小端(Little Endian:LE)。
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
union
{
short s;
char c[sizeof(short)];
} un;
un.s = 0x0102;
if ( sizeof(short) == 2 )
{
if (un.c[0] == 1 && un.c[1] == 2)
printf("Big-Endian\n");
else if (un.c[0] == 2 && un.c[1] == 1)
printf("Little-Endian\n");
else
printf("Unknown\n");
}
else
printf("sizeof(short) = %d\n", sizeof(short));
exit(0);
}
编译 && 运行:
Linux(LE):
$ uname -a
Linux localhost.localdomain 2.6.32-642.el6.x86_64 #1 SMP Tue May 10 17:27:01 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
$ gcc -o byte-order byte-order.c
$ ./byte-order
Little-Endian
HPUX(BE):
$ uname -a
HP-UX opel B.11.31 U ia64 2596713519 unlimited-user license
$ aCC -o byte-order byte-order.c
$ ./byte-order
Big-Endian
AIX(BE):
$ uname -a
AIX aix68113 1 6 00F7CAA94C00
$ xlc -o byte-order byte-order.c
$ ./byte-order
Big-Endian
注:代码参考自《UNIX网络编程卷一》。
2018.04.15更新
在看到htons等函数时,忽然想到还有个办法判断主机字节序。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
int main()
{
uint16_t HostByteOrder = 0x0102;
uint16_t NetByteOrder = htons(HostByteOrder);
if (HostByteOrder == NetByteOrder)
printf("Big Endian\n");
else
printf("Little Endian\n");
return 0;
}
Linux:
$ gcc -o main main.c
$ ./main
Little Endian
原理是:
我虽然不知道主机字节序是啥,但是我可以通过htons这样的函数,将其统一转换为网络字节序。
网络字节序是大端(BE)。
我拿转换前的数值和转换后的大端数值进行比较:
如果相等,说明当前主机字节序等价于网络字节序,BE;否则,当前主机字节序为LE。
需要注意:
构建主机字节序的数值时,不要使在LE和BE下都一样的数值,例如:
(16BIT):
0XFFFFFFFF
0XAABBBBAA
这样的数值,在LE和BE下数值都是相等的,=.=!!!