可能重複:
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