Sunday, January 15, 2012

Is your machine little or big endian? Find it out!!

Little endian is a multibyte hardware storage scheme where the most significant byte (the one whose bits contribute a bigger amount to the resulting number) is stored in the lower address. For instance, if an integer is represented with 4 bytes, the number 1 will be represented as:

memory address 0 1 2 3
Value 00000000 00000000 00000000 00000001
Big endian stores the most significant byte in the highest address. So, again our integer with decimal value 1 will be stored as the following binary number:

memory address 0 1 2 3
Value 00000001 00000000 00000000 00000000

Do you want to know if your machine stores numbers in Little or Big endian? The following C code will give you the answer:
#include

int isLittleEndian(){
// Create an integer with the least significant byte set to 1
int x = 0x0001;
// Get a pointer to the integer, interpret it as a byte, and see
// what it contains. So we are giving a look to the contents of the
// lowest memory address. If it contain the LSB then it is not
// little endian
if(*(char*)(&x)==1) return 0;
else return 1;
}

int main(){
printf("Is Little Endian: %s",(isLittleEndian())?"True":"False");
return 0;
}

Again, do not forget that endianness is a characteristic of the hardware.