可能重复:
How to check whether a system is big endian or little endian?大端或小端?
怎么知道现在用的机器是或大或小端?有没有我可以写的代码来做到这一点?
可能重复:
How to check whether a system is big endian or little endian?大端或小端?
怎么知道现在用的机器是或大或小端?有没有我可以写的代码来做到这一点?
以下代码应该会给你答案。
#include <stdio.h>
int main() {
long x = 0x44434241;
char *y = (char *) &x;
if(strncmp(y,"ABCD",4)){
printf("Big Endian\n");
}else{
printf("little Endian\n");
}
}
说明
在little endian
4个字节被存储为[4th, 3rd , 2nd, 1st]
。 0x41
是A
和0x42
是B
等等。这个bytestrem被解释为字符串,并且我们使用strncpy
来确定字节在机器中的实际排列方式,并决定它是否为little or big endian
。
int main()
{
unsigned int i = 0x12345678; // assuming int is 4 bytes.
unsigned char* pc = &i;
if (*pc == 0x12)
printf("Big Endian. i = 0x%x, *pc = 0x%x\n", i, *pc);
else if (*pc == 0x78)
printf("Little Endian. i = 0x%x, *pc = 0x%x\n", i, *pc);
return 0;
}
+1似乎这将比接受的答案更快。 – rzetterberg 2011-07-05 10:42:12
许多重复,例如, [如何检查系统是大端还是小端?](http://stackoverflow.com/questions/4181951/how-to-check-whether-a-system-is-big-endian-or-little- endian)和[在C++程序中以编程方式检测字节顺序](http://stackoverflow.com/questions/1001307/detecting-endianness-programmatically-in-ac-program) – 2011-03-25 12:59:45