大端还是小端?

时间:2011-03-25 12:38:48

标签: objective-c c

  

可能重复:
  How to check whether a system is big endian or little endian?

如何知道机器使用的是大端还是小端?有没有我可以写的代码呢?

2 个答案:

答案 0 :(得分: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 :(得分: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