Hello,
I'm going through the "UNIX network programming" by R.Stevens and stuck with
the following code, determining the endiannes of a host it is running on:
#include <stdio.h>
#include <stdlib.h>
#define CPU_VENDOR_OS "i686-pc-linux-gnu"
int main(void)
{
union {
short s;
char c[sizeof(short)];
} un;
un.s = 0x0102;
printf("%s: ", CPU_VENDOR_OS);
if (sizeof(short) == 2) {
if (un.c[0] == 1 && un.c[1] == 2)
printf("big-endian\n");
else if (un.c[0] == 2 && un.c[1] == 1)
printf("little-endian\n");
else
printf("unknown \n");
} else
printf("sizeof( short) = %d\n", sizeof(short));
exit(0);
}
What I don't get is how come that un.c[0] and un.c[1] both contain what has
been un.s initialized, i.e. 0x0102. Is it a feature of 'union'?
Why could not we use 'struct' to check how bytes are placed in memory ?
Thanks in advance!
With best regards, Roman Mashak. E-mail: mrv@tusur.ru
I'm going through the "UNIX network programming" by R.Stevens and stuck with
the following code, determining the endiannes of a host it is running on:
#include <stdio.h>
#include <stdlib.h>
#define CPU_VENDOR_OS "i686-pc-linux-gnu"
int main(void)
{
union {
short s;
char c[sizeof(short)];
} un;
un.s = 0x0102;
printf("%s: ", CPU_VENDOR_OS);
if (sizeof(short) == 2) {
if (un.c[0] == 1 && un.c[1] == 2)
printf("big-endian\n");
else if (un.c[0] == 2 && un.c[1] == 1)
printf("little-endian\n");
else
printf("unknown \n");
} else
printf("sizeof( short) = %d\n", sizeof(short));
exit(0);
}
What I don't get is how come that un.c[0] and un.c[1] both contain what has
been un.s initialized, i.e. 0x0102. Is it a feature of 'union'?
Why could not we use 'struct' to check how bytes are placed in memory ?
Thanks in advance!
With best regards, Roman Mashak. E-mail: mrv@tusur.ru
Comment