通过联合体 union
判断
#include <stdio.h>
int check_endianness() {
union {
unsigned int i;
unsigned char c[4];
} test;
test.i = 0x12345678;
// 如果第一个字节是 0x12,说明是大端;如果是 0x78,说明是小端
return test.c[0] == 0x12 ? 0 : 1;
}
int main() {
if (check_endianness()) {
printf("小端序\n");
} else {
printf("大端序\n");
}
return 0;
}
通过指针强制类型转换
#include <stdio.h>
int check_endianness() {
unsigned int x = 0x12345678;
unsigned char *c = (unsigned char *) &x;
// 如果第一个字节是 0x12,说明是大端;如果是 0x78,说明是小端
return *c == 0x12 ? 0 : 1;
}
int main() {
if (check_endianness()) {
printf("小端序\n");
} else {
printf("大端序\n");
}
return 0;
}
使用标准库 htons
和 ntohs
#include <stdio.h>
#include <arpa/inet.h>
int check_endianness() {
unsigned short x = 0x1234;
unsigned short y = htons(x); // 转换为网络字节序(大端)
// 如果转换后和原数相同,说明本地是大端,否则是小端
return x == y ? 0 : 1;
}
int main() {
if (check_endianness()) {
printf("小端序\n");
} else {
printf("大端序\n");
}
return 0;
}
通过位运算
#include <stdio.h>
int check_endianness() {
unsigned int x = 1;
// 如果最低位为 1 的字节在内存中的第一个字节处,则是小端序
return (*(char *)&x == 1) ? 1 : 0;
}
int main() {
if (check_endianness()) {
printf("小端序\n");
} else {
printf("大端序\n");
}
return 0;
}
通过字符数组
#include <stdio.h>
int check_endianness() {
unsigned int x = 0x01020304;
char *p = (char *)&x;
// 依次比较第一个字节的值
if (p[0] == 1 && p[1] == 2 && p[2] == 3 && p[3] == 4) {
return 0; // 大端序
} else {
return 1; // 小端序
}
}
int main() {
if (check_endianness()) {
printf("小端序\n");
} else {
printf("大端序\n");
}
return 0;
}