Tuesday, January 22, 2013

How to determine Endianness of a system programmatically

What is Endianness ?
Endianness is *in which order the system stores data bytes*.

For example, a Little Endian system will store lower byte of data on lower addresses of memory.

Little Endian example
Suppose an integer of 4 bytes.
Byte3 Byte2 Byte1 Byte0

Base_Address + 0 = Byte0
Base_Address + 1 = Byte1
Base_Address + 2 = Byte2
Base_Address + 3 = Byte3

Big Endian system stores upper data bytes in lower memory addresses.

Big Endian example
Suppose an integer of 4 bytes.
Byte3 Byte2 Byte1 Byte0

Base_Address + 0 = Byte3
Base_Address + 1 = Byte2
Base_Address + 2 = Byte1
Base_Address + 3 = Byte0

Interpret it like this,

int x = 1;
char * ptr = (char*)&x;

For a little endian system
ptr[0] will store 1

For a big endian system
ptr[0] will store 0

Note: ptr[0] is equivalent to dereferencing a pointer reference like this : *(ptr + 0)

Complete code

int x = 1;
char * ptr = (char*)&x;

if (*ptr == 1)
// little endian
else
// big endian