Pages1

C program to know "Endianess" of target (Underlying processor)

A C programmer often encounter to a situation where it is impetative to know the underlying processor type;
How processor treat with data while storing in memory in "Little Endian" format or in "Big Endian" format?

As we already aware of the fact that Network byte order is in "Big Endian" Format therefore while storing
Data one need to verify "Edianess" an then  need to execute program to store data.
Below is program which check "Endianess" of underlying processor/ target" and print same on the console.

Program is executed on X86 based processor:
--------------------------------------------------------------------------------------------------------


#include<stdio.h>

#define LITTLE_ENDIAN 0
#define BIG_ENDIAN      1

int endianness()
{
    long int i = 0x1; /* (0x00000001) */
    const char *p = (const char *) &i;
    if (p[0] == 1) /* Lowest address contains the least significant byte */
    {
        return LITTLE_ENDIAN;
    }
    else
    {
        return BIG_ENDIAN;
    }
}

int main ()
{
    int ret;
    ret = endianness();
    if ( LITTLE_ENDIAN == ret )
    {
        printf("\nI am Little Endian Processor\n");
    }
    else
    {
        printf("\nI am Big Endian Processor\n");
    }
}


Output on x86 Machine:
I am Little Endian Processor
-------------------------------------------------------------------------------------------------------
 





No comments:

Post a Comment