Skip to main content

Basics of Programming : Understanding Big Endian and Little Endian


Endianness refers to the sequential order in which bytes are arranged into larger numerical
values when stored in memory.

When we consider any multi byte value we know which is its LSB ( Least Significant Byte) and
which is MSB (Most Significant Byte) based on the arrangement of LSB or MSB in lower address
of the memory, the endianness is defined.

There are two ways in which multi byte values are stored in memory
  • Little Endian
  • Big Endian

Little Endian : If the lower byte (LSB) is stored in lower address of the memory this arrangement
is called as little endian

Big Endian : If the Higher byte (MSB) is stored in lower address of the memory this arrangement
is called as Big Endian.


For example,
 Consider a number 0x01020304, here least significant byte is 04 and most significant byte is 01.

This is how the arrangement in memory with two different endianness.

0x100
0x101
0x102
0x103
01
02
03
04
Big Endian

0x100
0x101
0x102
0x103
04
03
02
01
Little Endian


How do you find whether your machine is little endian or big endian ?

Below C Program can help you to know endianness of the machine


#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("\n");
}
 
/*Main function to call above function for 0x01234567*/
int main()
{
   int i = 0x01234567;
   show_mem_rep((char *)&i, sizeof(i));
   getchar();
   return 0;
}


When above program is run on little endian machine, gives “67 45 23 01” as output , while if it
is run on endian machine, gives “01 23 45 67” as output.


Comments

Post a Comment