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?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With