怎么判断大小端(网络字节序和主机字节序)
判断方式
使用union进行判断,这里说一下能用union判断的理由,union所占的字节数是union中成员的最大字节数,也就是说成员们共用同一块地址。
#include<stdio.h>
void byteOrder() {
union {
short data;
char value[2];
}test;
test.data = 0x0102;
if (test.value[0] == 1 && test.value[1] == 2) //低位高地址
printf("big endian\n");
else if (test.value[0] == 2 && test.value[1] == 1) //低位低地址
printf("little endian\n");
else
printf("oo\n");
}
int main() {
byteOrder();
return 0;
}
参考游双老师