Challenges/Memory & Types/Union as a Memory View

Union as a Memory View

๐ŸŸก Standard

Union as a Memory View

Implement a union that lets you view a `uint32_t` as its individual bytes, and a function `get_byte` that extracts the nth byte (0 = least significant).

typedef union {

uint32_t word;

uint8_t bytes[4];

} WordView;

Why it matters: This pattern is everywhere in embedded โ€” reading sensor registers, parsing CAN frames, interpreting protocol headers.

example
typedef union {
    uint32_t word;
    uint8_t  bytes[4];
} WordView;

Test Cases

1.
get_byte(0x12345678, 0) == 0x78 (little-endian)
get_byte(0x12345678, 0) == 0x78
2.
get_byte(0x12345678, 3) == 0x12
get_byte(0x12345678, 3) == 0x12
3.
get_byte(0xFF000000, 3) == 0xFF
get_byte(0xFF000000, 3) == 0xFF
solution.c