Sunday, August 17, 2014

Endianess ( Little Endian vs Big Endian )



representation of short (2bytes) number:
(0x0102)16 = (258)10 = (0000 0001 0000 0010)2 (MSB TO LSB memory representation)



  • (0000 0001 (value is 255) + 0000 0010 (value is 2) = 258. so when converting 258 decimal into binary and if store in the memory then memory representation will be like this(01 MSB or higher byte and 02 lower byte or LSB). If we represent this memory using 2 bytes character pointer means then char pointer of [0] represent the staring address A and char point of [1] represent the  next address (A+1)
  • As per the little endian and big endian definiton
  • Little Endian: In this scheme low-order byte is stored on the starting address (A) and high-order byte is stored on the next address (A + 1).
  • Big Endian: In this scheme high-order byte is stored on the started address (A) and low-order byte is stored on the next address (A+1).
  • here data stored in the meory as looking like in the hexa decimal or binary format(i.e LSB 02 first stored in memory and then MSB 01 stored in the memory). this is little endian order. if the hexa decimal value value stored in the memory as 0201 order means that is big endian
  • In which byte order the data stored in the memory differentiate the little endian and big endian
  • Example picutres



  • Simple program to find the endiness off the machine:
  • #include <stdio.h>
    int main()
    {
    unsigned int i = 1;
    char *c = (char*)&i;
    if (*c)
    	printf("Little endian");
    else
    	printf("Big endian");
    getchar();
    return 0;
    }
  • Example program:
#include <stdio.h>

int main(int argc, char **argv)
{
    union {
        short s;
        char c[sizeof(short)];
    }un;
    un.s = 0x0102;
    
    if (sizeof(short) == 2) {
        if (un.c[0] == 1 && un.c[1] == 2)
            printf("big-endian\n");
        else if (un.c[0] == 2 && un.c[1] == 1)
            printf("little-endian\n");
        else
            printf("unknown\n");
   } else{
        printf("sizeof(short) = %d\n", sizeof(short));
   }
   exit(0);
}



$> gcc byteorder.c
$> ./a.out
little-endian
$>

Source:



No comments:

Post a Comment