C Programming Basics
union { uint32_t w; uint8_t b[4]; } u;
u.w = 0x12345678;
printf("%02X %02X\n", u.b[0], u.b[1]);uint32_t and uint8_t are 32-bit and 8-bit unsigned integer types, and the environment is little-endian. Which of the following is the output when the code above is executed?
- A12 34
- B78 56
- C87 65
Show answer and explanation
Answer: B. 78 56
The members of a union overlap starting at the same address, so u.b[0] to u.b[3] each represent one of the 4 bytes of u.w. Little-endian places the least significant byte at the lowest address, so 0x12345678 is laid out as 78, 56, 34, 12 from the lowest address. So u.b[0] is 0x78 and u.b[1] is 0x56. Reading a member other than the one written can be used in this way to examine byte order, but the result depends on endianness.
- A. This is the output in a big-endian environment.
- B. Correct. The least significant byte, 0x78, is placed at the first address.
- C. The order of the bytes is reversed, but the upper and lower 4 bits within a byte are never swapped.