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;

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

    /*temp.bits.enable = e;
    temp.bits.mode = m;
    temp.bits.interrupt = i*/

    temp.reg |= (e<<0) | (m<<1) | (i<<3);

    printf("%d",temp.reg);
    // Construct and print register value
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

1 2 1

Expected Output

13