How to detect your computer's endianness?

This question tests your knowledge of computer architectures as much as it tests our ability to program. The interviewer wants to know if you are familiar with endian.
Endianness refers to the order in which a computer stores the bytes of a multibyte value.
In the Big Endian machine, the most-significant byte has the lowest address.
In the Little Endian machine, the least-significant byte has the lowest address.

The first way to program this is:
//Return 1, if the machine is little-endian, 0 if it is big-endian
int Endiannes(void){
int aInt;
char* chPtr;
aInt = 1;
chPtr = (char*) &aInt;
return *chPtr; //return the byte in the lowest address
}

The second way to tackle the problem is using UNION:
//return 1, the machine is little-endian
int Endianness(void){
union {
int aInt;
char singleByte;
} endianTest;
endianTest.aint = 1;
return endianTest.singleTest;
}


Reference:
Programming Interviews, John Mongan and Noah Suojanen

No comments:

Post a Comment