#include <iostream>
#include <cstdint>
using namespace std;
union Reg {
uint8_t raw;
struct {
uint8_t en : 1;
uint8_t mode : 3;
uint8_t reserved : 4;
} bits;
};
int main() {
unsigned int input;
cin >> input;
uint8_t val = static_cast<uint8_t>(input);
Reg r;
r.raw = val;
cout << "en=" << static_cast<int>(r.bits.en)
<< " mode=" << static_cast<int>(r.bits.mode);
return 0;
}
Explanation & Logic Summary:
The union Reg overlays a single 8-bit memory location with two views:
raw allows full-register accessbits allows named access to individual bit fieldsWriting to raw updates the bitfields automatically.
The explicit integer casts ensure that uint8_t bitfields are printed as numbers, not ASCII characters.
Firmware Relevance & Real-World Context:
This pattern directly mirrors how firmware interacts with:
Using unions with bitfields improves readability over manual masking and shifting while preserving low-level control—an essential embedded C++ skill.
Input
13
Expected Output
en=1 mode=6