148. ADC Sample Union View

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

struct AdcSample {
    uint32_t timestamp;
    union {
        uint16_t raw;
        struct {
            uint8_t lo;
            uint8_t hi;
        };
    };
};

int main() {
    uint32_t ts;
    uint16_t raw;

    cin >> ts >> std::hex >> raw;

    AdcSample sample;
    sample.timestamp = ts;
    sample.raw = raw;

    cout << "ts=" << sample.timestamp
         << " lo=0x" << uppercase << hex << setw(2) << setfill('0') << (int)sample.lo
         << " hi=0x" << uppercase << hex << setw(2) << setfill('0') << (int)sample.hi;

    return 0;
}

Explanation & Logic Summary:
The anonymous union allows the same 16-bit ADC value to be accessed either as a full word (raw) or as individual bytes (lo, hi) without additional naming. On little-endian systems, the least significant byte occupies the lowest address, mapping correctly to lo.

Firmware Relevance & Real-World Context:
This pattern is widely used in embedded firmware for:

  • Register overlays
  • Peripheral data decoding
  • Communication packet formatting
  • Memory-mapped I/O access

Anonymous unions reduce verbosity while preserving clarity and efficiency in low-level code.

 

 

 

 

Loading...

Input

1000 0x0000

Expected Output

ts=1000 lo=0x00 hi=0x00