top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How can I use C to check the endianess on my machine?

+1 vote
609 views
How can I use C to check the endianess on my machine?
posted Sep 5, 2013 by Luv Kumar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

3 Answers

+2 votes

Something like this:

unsigned short num;
unsigned char * array;

num = 0xFF00;
array = (char *) num;
if(array[0] = 0x00)
{
   printf("littileEndian");
}
else
{
   printf("bigEndian");
}
answer Sep 5, 2013 by Mandeep Sehgal
+1 vote
typedef enum   { 
  LITTLE_ENDIAN,
  BIG_ENDIAN
} endian;

endian check_endian(void)
{
  int x=1;
  if(*(char*)&x==1)
    return LITTLE_ENDIAN;
  else
    return  BIG_ENDIAN;
}
answer Sep 5, 2013 by Giri Prasad
0 votes

Doesnt the compiler know when it is compiling your program since it is required to have detailed knowledge about the target platform? Seems like the kind of thing you could check with a macro.

Looks like GCC defines __BYTE_ORDER__ and some associated macros:
http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html

answer Sep 5, 2013 by Bob Wise
...