Register Bitfields Using Struct Overlay

Code

#include <stdio.h>
#include <stdint.h>

// typedef union {
//     struct {
//         uint8_t enable    : 1;
//         uint8_t mode      : 2;
//         uint8_t interrupt : 1;
//         uint8_t reserved  : 4;
//     } bits;
//     uint8_t reg;
// } ControlRegister;


typedef union{

    struct{
        uint8_t enable: 1;
        uint8_t mode:2;
        uint8_t interrupt:1;
        uint8_t reserved:4;
    }bits;

    uint8_t reg;


}ControlRegister;


int main() {
    uint8_t e, m, i;
    scanf("%hhu %hhu %hhu", &e, &m, &i);

    ControlRegister conf;

    conf.bits.enable =e;
    conf.bits.mode = m;
    conf.bits.interrupt = i;


    //ctrl.bits.reserved=0x00;  -- This should be htere

    printf("%hhu", conf.reg);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

1 2 1

Expected Output

13