Background
One of my junior who is working with ST Microelectronics, Noida was asked this question in her interview. I am describing my approach to solve this question.

Fundamentals First

"Computer architecture supports two different memory storage techniques based on order of bytes in which data is stored in memory". e.g. In a two byte number 0xC06E
'C0' is Most Significant Byte (MSB) of this number.
'6E' is Least Significant Byte (LSB) of this number.
It is either saved with LSB first or MSB first.

Machines that store LSB first are Little Endian machines (6E C0)
And, Machines that store MSB first are Big Endian machines (C0 6E)

Tip: Intel Machines are Little Endian and PowerMac (Apple) are Big Endian.

Problem Definition
Write a piece of code that when compiled and executed on a machine tells whether machine is Little Endian or Big Endian.

Solution:
There are two ways we can achieve this by writing code. One, using Pointers and Second, using Unions (generally one of the less used feature of C).

Basic idea behind both these approaches is to assign a value of 1 to a multi-byte data type say int. And then check the first byte of memory address where multi-byte number is saved.

Approach 1
: Using Pointers.


#include<stdio.h>
#include<stdlib.h>
int isLittleEndian()
{
int intVal = 1;
int *ptrToInt = &intVal;
char *ptrToChar =(char *) ptrToInt;
if(*ptrToChar == 0)
return 0;
return 1;

}
int main()
{
if(isLittleEndian())
printf("Machine is Little Endian\n");
else
printf("Machine is Big Endian\n");
system("pause");
}


Approach 2: Using UNION


#include<stdio.h>
#include<stdio.h>
#include<stdlib.h>
union
{
int a;
char b;
}testUnion;

int isLittleEndian()
{
testUnion.a = 1;
if(testUnion.b == 0)
return 0;
return 1;

}
int main()
{
if(isLittleEndian())
printf("Machine is Little Endian\n");
else
printf("Machine is Big Endian\n");
system("pause");
}


If you have any query/question or feedback. Feel free to send them over to codeboat@gmail.com

1 comments

  1. shan // October 1, 2008 at 2:23 PM  

    I was also asked the same question in Adobe. I went for the solution#1.
    I believe we can do something like this with bit operations too. Anyways, every technique results in the same logic.
    With this, we should also be aware of Middle Endianness. You can scribble something about that too.