Interview Questions

How can I determine whether a machines byte order is big-endian or little-endian?

C Interview Questions and Answers


(Continued from previous question...)

How can I determine whether a machines byte order is big-endian or little-endian?

The usual techniques are to use a pointer:
int x = 1;
if(*(char *)&x == 1)
printf("little-endian\n");
else printf("big-endian\n");

or a union:

union {
int i;
char c[sizeof(int)];
} x;
x.i = 1;
if(x.c[0] == 1)
printf("little-endian\n");
else printf("big-endian\n");

(Note that there are also byte order possibilities beyond simple big-endian and little-endian

(Continued on next question...)

Other Interview Questions