Thursday 12 March 2015

C Program to Find the Endianness of a Machine



Endianness is the ordering or sequencing of bytes of a word of digital data in computer memory storage or during transmission. Words may be represented in big-endian orlittle-endian manner. Big-endian systems store the most-significant byte of a word at the smallest memory address and the least significant byte at the largest. Little-endian system, in contrast, stores the least-significant byte at the smallest address.

In this post I have given a C program to find out the Endianness of your system. The program is given below.



int main()
{
    int x = 1;
    if(*(char *)&x == 1)
    {
        printf("little-endian\n");
    }
    else
    {
        printf("big-endian\n");
    }
    return 0;
}

The program finds the Endianness by using the size of integer variables and a character variables. The integer variable holds the value 1. Then this integer variable is cast into a character and if the value of this character  is 1 you have a little-endian machine. If the character    is 0 then you have a big-endian machine. What is the working principle of this program? When you cast an integer to char the lowest addressed byte of the integer is used a char variable. If this lowest addressed byte contains the value 1 then the machine is little-endian, otherwise it is a big-endian machine. Why so? The integer 1 is represented as 00000000 00000000 00000000 00000001 in a 4 byte int. When you cast this int variable as a char the lowest address contains 00000001 in little-endian and 00000000 in big-endian. Hence if the value of the character variable is 1 you have a little-endian system and if the value of the character variable is 0 you have a big-endian system.