Identifying Big Endian or Little Endian Progmatically


Most (99%+) of microprocessors available to the consumer and/or embedded market are either Big Endian or Little Endian; this almost never actually matters. However, sometimes one needs to write endian specific code. Here’s how to have code identify if it’s running on a big endian or little endian machine:

First, a little review. When a computer stores a multi-byte digit in memory, it can do so in one of two ways:
Big Endian, which means that the MSB (most significant byte) is stored first, in the lowest memory address OR
Little Endian, which means that the LSB (least significant byte) is stored first, in the lowest memory address.
For example, if we have the number 0x0123ABCD, a Big Endian machine (such as a PowerPC) will store it as 0x01, 0x23, 0xAB, 0xCD; a Little Endian machine (such as an Intel x86) will store it in memory as 0xCD, 0xAB, 0x23, 0x01.

To determine if a machine is big or little endian, we can cast a 4 byte integer to a 1 byte character. In a little endian machine, the integer 1 is stored as 0x01 0x00 0x00 0x00. Thus, casting it to a one byte character will return 0x01.

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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *