C program to check little vs. big endian

ordinary picture ordinary · Oct 9, 2012 · Viewed 159k times · Source

Possible Duplicate:
C Macro definition to determine big endian or little endian machine?

int main()
{
  int x = 1;

  char *y = (char*)&x;

  printf("%c\n",*y+48);
}

If it's little endian it will print 1. If it's big endian it will print 0. Is that correct? Or will setting a char* to int x always point to the least significant bit, regardless of endianness?

Answer

Marcus picture Marcus · Oct 9, 2012

In short, yes.

Suppose we are on a 32-bit machine.

If it is little endian, the x in the memory will be something like:

       higher memory
          ----->
    +----+----+----+----+
    |0x01|0x00|0x00|0x00|
    +----+----+----+----+
    A
    |
   &x

so (char*)(&x) == 1, and *y+48 == '1'.

If it is big endian, it will be:

    +----+----+----+----+
    |0x00|0x00|0x00|0x01|
    +----+----+----+----+
    A
    |
   &x

so this one will be '0'.