Register Bitfields Using Struct Overlay

Use union to overlay the bitfields.

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

union Control_8bit{
    struct{
        uint8_t en : 1;
        uint8_t mode : 2;
        uint8_t inter : 1;
        uint8_t res : 4;
    }bits;
    uint8_t raw_data;
};

int main() {
    uint8_t e, m, i;
    union Control_8bit Register = {0};
    scanf("%hhu %hhu %hhu", &e, &m, &i);
    // Construct and print register value

    Register.bits.en = e;
    Register.bits.mode = m;
    Register.bits.inter = i;
    Register.bits.res = 0;      //reserved initialized to 0, no need now
    
    printf("%u", Register.raw_data);
    

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

1 2 1

Expected Output

13