58. Byte Splitter Union Basics

#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;
}

Solution Details

  • The union overlays memory: word and bytes[2] occupy the same location.
  • Writing to word makes the bytes[] reflect the same data at the byte level.
  • On little-endian systems:
    • bytes[0] = LSB (least significant byte)
    • bytes[1] = MSB (most significant byte)
       

👉 In simple words: The union is two “views” of the same memory — one as a full 16-bit value, one as two 8-bit chunks.
 

Significance for Embedded Developers

  • Useful in UART/I²C/SPI communication when a 16-bit register must be transmitted as two bytes.
  • Common in embedded protocols (Modbus, CAN, etc.).
  • Saves CPU cycles compared to shifting and masking.
     
Loading...

Input

4660

Expected Output

LSB=52 MSB=18