Thursday, 28 November 2013

Understanding Endian – Little Endian and Big Endian

Endian – It is a term refers to the order in which the bytes are stored in memory.
There are two different architectures for handling memory storage.
  • Little Endian.
  • Big Endian.

Little Endian
In simple - Little End First.
This means a Hex word like 0x1234 is stored in memory as (0x34 0x12). The little end, or lower end, is stored first. Windows NT works only in the Little Endian mode on both computers. 

Big Endian
In simple -Big End First.
Big Endian does this in the reverse fashion, so 0x1234 would be stored as (0x12 0x34) in memory. This is the method used by Motorola computers and can also be used on RISC-based computers. The RISC-based MIPS computers and the DEC Alpha computers are configurable for Big Endian or Little Endian.

In computing, memory commonly stores binary data by splitting it into 8 bit units (bytes).

Base address of “data”:




 







LSB byte is stored first in the memory as shown above.

/* checking the data stored in memory using c program */
#include <stdio.h>

int main(void){
    int i;
    int data = 0x12345678;
    char *ptr = &data;
    printf("Data  Index(Address)\n");
    for(i = 0; i < 4; i++, ptr++){
        printf(" %x -> 0x%x\n", (int)*ptr, ptr);
    }
    return 0;
}

Output:
As shown above




Since “data” is int data type, it will occupy 4 bytes continuous memory with the base address 0x0039fd44. Each byte of memory is associated with an index, called its address, which indicates its position. Bytes of a single data word (such as a 32 bit integer data type) are generally stored in consecutive memory addresses (a 32 bit int needs 4 such locations).

In case of Big Endian “data” will be stored in the memory as shown below.











Find the Endianness through c program.
/* Program to find Endianness using pointer */
#include <stdio.h>

int main(void){
    unsigned int data = 1;
    char *ptr = (char *)&data;
    if(*ptr)
        printf("Little Endian\n");
    else
        printf("Big Endian\n");
    return 0;

}

No comments:

Post a Comment