Consider the following C code that checks the endianness of the system:
unsigned int x = 0x12345678;
char *c = (char*)&x;
printf("%02x %02x %02x %02x", (unsigned char)c[0], (unsigned char)c[1], (unsigned char)c[2], (unsigned char)c[3]);What will be printed on a little-endian system?
unsigned int x = 0x12345678; char *c = (char*)&x; printf("%02x %02x %02x %02x", (unsigned char)c[0], (unsigned char)c[1], (unsigned char)c[2], (unsigned char)c[3]);
Think about how bytes are stored in memory on little-endian systems.
In little-endian systems, the least significant byte is stored first. So 0x12345678 is stored as 78 56 34 12 in memory.
Given the same code as before:
unsigned int x = 0x12345678;
char *c = (char*)&x;
printf("%02x %02x %02x %02x", (unsigned char)c[0], (unsigned char)c[1], (unsigned char)c[2], (unsigned char)c[3]);What will be printed on a big-endian system?
unsigned int x = 0x12345678; char *c = (char*)&x; printf("%02x %02x %02x %02x", (unsigned char)c[0], (unsigned char)c[1], (unsigned char)c[2], (unsigned char)c[3]);
Recall how big-endian systems store the most significant byte first.
Big-endian systems store the most significant byte first, so 0x12345678 is stored as 12 34 56 78 in memory.
Choose the correct statement about endianness in computer systems.
Think about which byte is stored first in memory for little-endian systems.
Little-endian systems store the least significant byte at the lowest memory address, while big-endian systems store the most significant byte first.
Consider this code snippet that tries to convert a 4-byte array to an integer:
unsigned char bytes[4] = {0x12, 0x34, 0x56, 0x78};
unsigned int *p = (unsigned int*)bytes;
printf("%x", *p);What problem might occur on a little-endian system?
Think about how the bytes are interpreted when cast to an integer pointer on little-endian.
The bytes are stored as 12 34 56 78. On little-endian, *p interprets it as 0x78563412 (LSB first), but if intended as big-endian serialization of 0x12345678, it's incorrect.
Which of the following C functions correctly swaps the byte order of a 32-bit unsigned integer (converts big-endian to little-endian or vice versa)?
Think about shifting and masking each byte to its new position.
Option D correctly shifts and masks each byte to swap the endianness. Option D incorrectly shifts without masking, causing bits to overlap. Option D just flips bits, not bytes. Option D has incorrect masking and shifting order.