Little and Big Indian Architecture

In Daily life we right One Hundred Twenty Three as "1 2 3" with the hundred digit 1 left-most. This is big endian convention.
The little-endian way of writing the same number would be to put the ones digit 3 in the left-most position: "3 2 1".


little-endian: lower bytes first
big-endian: higher bytes first 


Consider the storage of the value ABCD
Here,

A-MSB(Most Significant Byte).
B
C
D-LSB(Least Significant Byte).

In Little Endian Architecture, LSB is at the lowest address of the memory location. Suppose memory location starts with 0
D->0
C->1
B->2
A->3
Intel Processors(CPUs) are Little Endian.

In Big Endian Architecture, MSB is at the lowest address of the memory location. As shown below.
A->0
B->1
C->2
D->3
While Motorola 680x0 CPUs are big-endian



What happens when little and big endian machine communicate each other ?




Constructing Messages - Byte Ordering :


Solution: Network Byte Ordering
Host Byte-Ordering: the byte ordering used by a host (big or little)
Network Byte-Ordering: the byte ordering used by the network –always big-endian
  • u_long htonl(u_long x);
  • u_short htons(u_short x);
  • u_long ntohl(u_long x);
  • u_short ntohs(u_short x);
On big-endian machines, these routines do nothing
On little-endian machines, they reverse the byte order
 


How to see memory representation of multibyte data types on your machine?
 
A sample C code that shows the byte representation of int, float and pointer.

#include <stdio.h>
/* function to show bytes in memory, from location start to start+n*/
void 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 0x12345678*/
int main()
{
   int i = 0x12345678;
   mem_rep((char *)&i, sizeof(i));
   getchar();
   return 0;
}
When above program is executed on little endian machine, gives “78 56 34 12" as output , while if it is executed on big endian machine, gives “12 34 56 78" as output.

There is a quick way to determine endianness of your machine?

#include <stdio.h>
int main()
{
   unsigned int x = 1;
   char *c = (char*)&x;
   if (*c)   
       printf("Little Endian");
   else
       printf("Big Endian");
   getchar();
   return 0;
}
Based on compiler if integer size is 4 byte then :
x in binary format
(Big Endian):     00000000 00000000 00000000 00000001 
(Little Endian) : 00000001 00000000 00000000 00000000
(char*)&x =  00000001 00000000-->(Little Endian)   00000000 00000000--->(Big Endian)

In the above program, a character pointer c is pointing to an integer x. Since size of character is 1 byte when the character pointer is de-referenced it will contain only first byte of integer. If machine is little endian then *c will be 1 (because last byte is stored first) and if machine is big endian then *c will be 0.



 

No comments:

Post a Comment