2011-03-25 72 views
2

可能重複:
How to check whether a system is big endian or little endian?大端或小端?

怎麼知道現在用的機器是或大或小端?有沒有我可以寫的代碼來做到這一點?

+0

許多重複,例如, [如何檢查系統是大端還是小端?](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

回答

3

以下代碼應該會給你答案。

#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]0x41A0x42B等等。這個bytestrem被解釋爲字符串,並且我們使用strncpy來確定字節在機器中的實際排列方式,並決定它是否爲little or big endian

+0

儘管它確實有效,但它具有使用函數調用。簡單地解引用字符指針,從而查看第一個「字符」就足夠了。 – DarkDust 2011-03-25 12:51:32

+0

這個例子比wikipedia文章更好理解。我已經閱讀過這麼多次,但是這幾行代碼基本上總結了我需要知道的一切。 – XMight 2014-12-26 11:53:27

6
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

+1似乎這將比接受的答案更快。 – rzetterberg 2011-07-05 10:42:12