Little Endian or Big Endian?

Question: Is your machine little or big endian?

Answer: Let first take a look at the solution before we discuss about it.

int isLittleEndian( void )
{
    unsigned int temp = 0x12345678;
    char * tempAddress = &temp;
    if( *tempAddress == 0x12 )
    {
        return 0; // Indicating False
    } else {
        return 1; // Indicating True
    }
}

To answer this, you have to obviously know what little and big endian are. Also you need some basic understanding of variable assignments for data types of varying sizes. A major mistake which you could make is with the temp variable. When I was asked this question, I answered it by taking a fixed address for temp which is insanely dangerous (I know I was dumb). The address could have been used for something else or even been a reserved address for all you know. By creating a local variable, temp will be placed on the stack so we don’t have to worry about whether it will be safe or not.

If you have any questions, please feel free to send me an email at support@mytechinterviews.com. If you have any interview questions which you feel would benefit others, I would love to hear about it.

2 Comments

2 Responses

  1. zeah says:

    need to cast the pointer
    char * tempAddress = (char *) &temp

  2. Sunil Verma says:

    same test but different value to initialize:

    unsigned int temp = 0×1;
    char * tempAddress = &temp;
    if( *tempAddress )

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>