62. Status or Code Dual View

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

struct Status {
    union {
        uint16_t code;
        struct {
            uint8_t low;
            uint8_t high;
        };
    };
    bool ok;
};

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

    Status s;
    s.code = c;
    s.ok = (s.code == 0);

    cout << "low=" << (int)s.low
         << " high=" << (int)s.high
         << " ok=" << (s.ok ? "true" : "false");
    return 0;
}

 

Solution Details

  • The anonymous union overlays memory: code and {low, high} are two ways to view the same 16-bit data.
  • Writing to code immediately sets low and high.
  • ok is set to true if the status code is zero, otherwise false.
     

👉 In simple words: It’s like having a short status word that you can read whole (code) or as two bytes (low, high). The ok flag adds a quick validity check.

 

Significance for Embedded Developers

  • Status or error codes are often 16-bit values in firmware.
  • Sometimes you need the whole code, other times you just need the low/high byte to send over a protocol.
  • The ok field is a practical pattern: flagging if the code means “all good” or “error.”
Loading...

Input

258

Expected Output

low=2 high=1 ok=false