如何用C语言代码判断字节编址是大端模式还是小端模式,请举三种方法
时间: 2024-03-21 21:44:03 浏览: 92
方法一:使用联合体实现大小端判断
```c
#include <stdio.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) = %lu\n", sizeof(short));
}
return 0;
}
```
方法二:使用指针强制类型转换实现大小端判断
```c
#include <stdio.h>
int main() {
short s = 0x0102;
char *p = (char*)&s;
if (*p == 1 && *(p + 1) == 2) {
printf("big-endian\n");
} else if (*p == 2 && *(p + 1) == 1) {
printf("little-endian\n");
} else {
printf("unknown\n");
}
return 0;
}
```
方法三:使用位运算实现大小端判断
```c
#include <stdio.h>
int main() {
short s = 0x0102;
char *p = (char*)&s;
if ((p[0] << 8 | p[1]) == s) {
printf("big-endian\n");
} else if ((p[1] << 8 | p[0]) == s) {
printf("little-endian\n");
} else {
printf("unknown\n");
}
return 0;
}
```
阅读全文