60. Register Overlay byte and bitfield

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

union Reg {
    uint8_t raw;
    struct {
        unsigned en : 1;
        unsigned mode : 3;
        unsigned reserved : 4;
    } bits;
};

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

    Reg r;
    r.raw = val;

    cout << "en=" << r.bits.en << " mode=" << r.bits.mode;
    return 0;
}

 

Solution Details

  • The union Reg overlays the same byte as both a raw value (raw) and a struct with bitfields.
  • Writing to raw updates the fields in bits.
  • en extracts bit 0, mode extracts bits 1–3, reserved covers the upper bits.
  • Example: 13 = 0b00001101 → en=1, mode=6.
     

👉 In simple words: It’s like having two ways to look at the same register — one as a single 8-bit number, another as named fields.

 

Significance for Embedded Developers

  • Hardware registers are often documented as bitfields in datasheets.
     
  • This union technique makes firmware clearer and safer, allowing direct access to flags (en) or modes (mode) without manual masking/shifting.
     

Still lets you read/write the whole register via raw when needed.
 

Loading...

Input

13

Expected Output

en=1 mode=6