Litte Endian , Big Endian Formats in C

    Endianness is byte ordering used to store the data in memory ie which byte has to be stored at the lower order address or the higher address.Here is a simple code given to determine the platform is which endian type.
==========
#include <stdio.h>
#include <stdlib.h>
#define STR_LIM (5)
#define STR_MAX_SIZE (256)

enum endian
{
    eBIG_ENDIAN,
    eLITTLE_ENDIAN,
};
char *int2char(int value);
int findEndian(int data);

int main()
{
    char string[STR_LIM] = "TEST";
    char testStr[5];
    int  number = 2048;
    printf(" Address : Value Representation\n");
    printf("-------------------------------\n");
    printf("%d:%c , %d:%c, %d:%c, %d:%c \n",&string[0],string[0],&string[1],string[1],&string[2],string[2],&string[3],string[3]);
    strcpy(testStr,int2char(number));
    printf("%d:%c , %d:%c, %d:%c, %d:%c \n",&testStr[0],testStr[0],&testStr[1],testStr[1],&testStr[2],testStr[2],&testStr[3],testStr[3]);
    if(findEndian(1))
    printf("LITTLE Endian Platform found\n");
    else printf("BIG Endian Platform found\n");
    return(getchar());
}

/* Integer to char conversion */
char *int2char(int value)
{
    static char string[STR_MAX_SIZE];
    sprintf(string,"%d",value);
    return string;
}

/* Check Which Endian the Platform is */
int findEndian(int data)
{
    char *charData;
    int ret = eLITTLE_ENDIAN;
    charData = (char *) &data;
    if(charData[0] == eBIG_ENDIAN)
    ret = eBIG_ENDIAN;
    return ret;
}

No comments: