Little Endian vs Big Endian

A question very frequently asked in interviews.

Lets keep it short & easy! Understand it once & for all!!

What are they?

Little Endian and Big endian are two ways of storing multi-byte data-types ( int, float, etc) in computers.

What’s the difference?

In Little Endian machines, last byte of binary representation of the multi-byte data-type is stored first while in Big Endian machines, first byte of binary representation of the multi-byte data-type is stored first.

For example:

Suppose an integer is stored as 4 bytes(32-bits), then a variable y with value 0x01234567( Hexa-decimal representation) is stored as four bytes 0x01, 0x23, 0x45, 0x67, on Big-endian while on Little-Endian (Intel x86), it will be stored in reverse order:

Example: How 0x1234567 is stored at memory location 0x100-ox103

How to check memory representation of multi-byte data-types on your machine?

Here is a sample C code that shows the byte representation of int (integer data type) of the machine it is executed on.

Copy and execute this yourself!!

#include <stdio.h>

/* function to show bytes in memory, from location start to start+n*/

void show_mem_rep(char *start, int n){

int i;

for (i = 0; i < n; i++)

printf(" %.2x", start[i]);

printf("

");

}

/*Main function to call above function for 0x01234567*/

int main(){

int i = 0x01234567;

show_mem_rep((char *)&i, sizeof(i));

return 0;

}

How to remember?

Source: fundd.blogspot.in. Little Endian, things are stored in reverse order.

Which is better? (The question you will be asked)

Both have advantages and disadvantages:

In “Little Endian” form, assembly language instructions for picking up a 1, 2, 4, or longer byte number proceed in exactly the same way for all formats: first pick up the lowest order byte at offset 0. Also, because of the 1:1 relationship between address offset and byte number (offset 0 is byte 0), multiple precision math routines are correspondingly easy to write.

In “Big Endian” form, by having the high-order byte come first, you can always test whether the number is positive or negative by looking at the byte at offset zero. You don’t have to know how long the number is, nor do you have to skip over any bytes to find the byte containing the sign information. The numbers are also stored in the order in which they are printed out, so binary to decimal routines are particularly efficient.