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 [email protected]. If you have any interview questions which you feel would benefit others, I would love to hear about it.

If you're looking for some serious preparation for your interviews, I'd recommend this book written by a lead Google interviewer. It has 189 programming questions and solutions:

Book Cover

3 Responses

  1. Balaji says:

    The below mentioned method will be more efficient as it uses only the memory for integer.

    union A
    int i;
    char c;

    AA.i = 0x12345678;
    if(c == 0x12)

  2. zeah says:

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

  3. Sunil Verma says:

    same test but different value to initialize:

    unsigned int temp = 0x1;
    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>