158. Byte Splitter Union

#include <iostream>
#include <cstdint>
using namespace std;

union ByteSplitter {
    uint16_t word;
    uint8_t bytes[2];
};

int main() {
    uint16_t val;
    cin >> val;

    ByteSplitter u;
    u.word = val;

    cout << "LSB=" << (int)u.bytes[0] << " MSB=" << (int)u.bytes[1];
    return 0;
}

Explanation & Logic Summary:

The union overlays memory so that word and bytes[] share the same address.

Writing to word allows direct access to its individual bytes.

On little-endian systems:

  • bytes[0] stores the least significant byte
  • bytes[1] stores the most significant byte

This technique avoids shifting and masking when splitting multi-byte data.

Firmware Relevance & Real-World Context:

  • Common in UART, SPI, I²C data framing
  • Used for register access and protocol payloads
  • Demonstrates memory layout awareness
  • Reinforces endianness considerations in firmware design

 

 


 

Loading...

Input

4660

Expected Output

LSB=52 MSB=18