2011-03-25 28 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