204. Union

Question.5

A developer writes portable code to extract bytes from a uint16_t:

Approach A -- union:

union { uint16_t val; uint8_t b[2]; } u;
u.val = 0x1234;
uint8_t high = u.b[1], low = u.b[0];

Approach B -- bitwise:

uint16_t val = 0x1234;
uint8_t high = (val >> 8) & 0xFF;
uint8_t low  = val & 0xFF;

Which approach is portable across big-endian and little-endian platforms?

Need Help? Refer to the Quick Guide below

Select Answer