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?

  1. A12 34
  2. B78 56
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. Which of the following is the output when the code above, which stores 9 in a 3-bit bit-field, is executed?
  2. Which of the following is the output when the code above, which uses the macro SQUARE defined with #define, is executed?
  3. The header file sensor.h is written as above. Which of the following is the purpose of the three lines #ifndef, #define and #endif?
  4. Which of the following is the output when the code above is written inside the main function and executed?
  5. A microcontroller output register is declared and used as above. Which of the following correctly describes this declaration?