Reviewing yesterday’s interview question – how to determine the endianness of a deviceYesterday, the interviewer first asked me what endianness is, and I confidently answered that big endian stores the low-order byte at the high memory address, while little endian stores the low-order byte at the low memory address.For example, the data 0x12345678 is stored in memory as follows in both endianness:
Then the interviewer shifted the topic and asked how to write a program to determine the device’s endianness. At that moment, I could only think of one method, which is shown below:First, initialize an integer num=1, then use a char pointer byte to point to the address of num. If the value of byte equals 1, it indicates that the low-order byte is at the low address, meaning it is little endian; if byte equals 0, it indicates big endian.
int num = 1; // Hexadecimal representation is 0x00000001 char *byte = (char *)# // Get the address of the first byte if (*byte == 1) { printf("Little-Endian\n"); } else { printf("Big-Endian\n"); }
In fact, there is another method using unions. By utilizing the shared memory feature of unions, the fundamental principle is the same as the method above.
union EndianCheck { int value; char bytes[sizeof(int)];};// Share 4 bytes of memoryint main() { union EndianCheck ec; ec.value = 1; if (ec.bytes[0] == 1) { printf("Little-Endian\n"); } else { printf("Big-Endian\n"); } return 0;}