61. ADC Result View Anonymous Union

#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" << hex << uppercase << (int)sample.lo
         << " hi=0x" << hex << uppercase << (int)sample.hi;
    return 0;
}

 

Solution Details

  • The anonymous union allows accessing raw directly, or its subfields (lo, hi) without needing extra dot notation like sample.u.lo.
  • Writing to raw immediately updates lo and hi.
  • Example: raw = 0x03F2 → lo = 0xF2, hi = 0x03.
     

👉 In simple words: The union lets you look at the same ADC reading as either a full 16-bit number or split into low/high bytes — and the anonymous union saves you from typing an extra union name.

 

Significance for Embedded Developers

  • Often ADC or peripheral data registers are 16-bit wide, but protocols or buffers require splitting into bytes.
  • Anonymous unions make firmware code shorter and cleaner, e.g., sample.lo instead of sample.u.lo.
  • Useful in designing packet formats or direct register overlays.
Loading...

Input

1000 0x03F2

Expected Output

ts=1000 lo=0xF2 hi=0x3