While I do understand endianness, I am slightly unclear on how the code works below. I guess this question is less about endianness and more about how the char * pointer and int work i.e. type conversion. Also, would it have made any difference if the variable word was not a short but just an int? Thanks!
#define BIG_ENDIAN 0
#define LITTLE_ENDIAN 1
int byteOrder() {
short int word = 0x0001;
char * byte = (char *) &word;
return (byte[0] ? LITTLE_ENDIAN : BIG_ENDIAN);
}
A short int is made up of two bytes, in this case
0x00and0x01. On a little endian system, the small byte comes first, so in memory it appears as0x01followed by0x00. Big endian systems are, naturally, reversed. This is what the pointers look like for short integers on a little endian system:Char pointers, on the other hand, are always incremented sequentially. Thus, by taking the address of the first byte of the integer and casting it to a
char *pointer, you may increment through each byte of the integer in memory-order. Here’s the corresponding diagram: