2

Possible Duplicate:
How to check whether a system is big endian or little endian?

how to know whether the machine am using is big or little endian? Is there a code i can write to do that?

Community
  • 1
  • 1
phoenix
  • 549
  • 1
  • 7
  • 21
  • Numerous duplicates, e.g. [How to check whether a system is big endian or little endian?](http://stackoverflow.com/questions/4181951/how-to-check-whether-a-system-is-big-endian-or-little-endian) and [Detecting endianness programmatically in a C++ program](http://stackoverflow.com/questions/1001307/detecting-endianness-programmatically-in-a-c-program) – Paul R Mar 25 '11 at 12:59

2 Answers2

6
int main()
{
  unsigned int i = 0x12345678; // assuming int is 4 bytes.
  unsigned char* pc = (unsigned char*) &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;
}
yasouser
  • 5,113
  • 2
  • 27
  • 41
3

Following code should get you the answer.

#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");
  }
}

Explanation

In little endian 4 bytes are stored as [4th, 3rd , 2nd, 1st]. 0x41 is A and 0x42 is Band so. This bytestrem is interpreted as character string and using strncpy we determine how bytes are actually arranged in machine and decide is its little or big endian.

Zimbabao
  • 8,150
  • 3
  • 29
  • 36
  • While it surely works, it has the disadvantage of using a function call. Simply dereferencing the char pointer and thus looking at the first "character" is enough. – DarkDust Mar 25 '11 at 12:51
  • This example is even better and simpler to understand than the wikipedia article. I've read the one so many times, but these few lines of code summarized basically everything I needed to know. – XMight Dec 26 '14 at 11:53