Register Overlay byte and bitfield

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

// define the union with bitfields
union Reg {
    uint8_t raw;
    struct {
        uint8_t en : 1;
        uint8_t mode : 3;
        uint8_t reserved : 4;
    } bits;
};

int main() {
   int val;
   cin >> val;
   Reg r;
   r.raw = static_cast<uint8_t>(val);   // ensure value fits in 8 bits
   cout << "en=" << static_cast<int>(r.bits.en)
        << " mode=" << static_cast<int>(r.bits.mode);
   return 0;
}
Upvote
Downvote
Loading...

Input

13

Expected Output

en=1 mode=6