So I’m writing a program to test the endianess of a machine and print it.
I understand the difference between little and big endian, however, from what I’ve found online, I don’t understand why these tests show the endianess of a machine.
This is what I’ve found online. What does *(char *)&x mean and how does it equaling one prove that a machine is Little-Endian?
int x = 1;
if (*(char *)&x == 1) {
printf("Little-Endian\n");
} else {
printf("Big-Endian\n");
}
If we split into different parts:
&x: This gets the address of the location where the variablexis, i.e.&xis a pointer tox. The type isint *.(char *)&x: This takes the address ofx(which is aint *) and converts it to achar *.*(char *)&x: This dereferences thechar *pointed to by&x, i.e. gets the values stored inx.Now if we go back to
xand how the data is stored. On most machines,xis four bytes. Storing1inxsets the least significant bit to1and the rest to0. On a little-endian machine this is stored in memory as0x01 0x00 0x00 0x00, while on a big-endian machine it’s stored as0x00 0x00 0x00 0x01.What the expression does is get the first of those bytes and check if it’s
1or not.