Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this C function to find the endianness of a machine at runtime?

Tags:

c

endianness

This is what I offered at an interview today.

int is_little_endian(void)
{
    union {
        long l;
        char c;
    } u;

    u.l = 1;

    return u.c == 1;
}

My interviewer insisted that c and l are not guaranteed to begin at the same address and therefore, the union should be changed to say char c[sizeof(long)] and the return value should be changed to u.c[0] == 1.

Is it correct that members of a union might not begin at the same address?

like image 758
sigjuice Avatar asked Aug 20 '09 02:08

sigjuice


1 Answers

I was unsure about the members of the union, but SO came to the rescue.

The check can be better written as:

int is_bigendian(void) {
    const int i = 1;
    return (*(unsigned char*)&i) == 0;
}

Incidentally, the C FAQ shows both methods: How can I determine whether a machine's byte order is big-endian or little-endian?

like image 200
Sinan Ünür Avatar answered Oct 09 '22 23:10

Sinan Ünür