Register Bitfields Using Struct Overlay

Code

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

typedef union {
    struct {//a struct with bit fields
        uint8_t enable    : 1;
        uint8_t mode      : 2;
        uint8_t interrupt : 1;
        uint8_t reserved  : 4;
    } bits;
    uint8_t reg;//a raw 1 byte register
} ControlRegister;//union

int main() {
    uint8_t e, m, i;
    scanf("%hhu %hhu %hhu", &e, &m, &i);//read values for enable, mode, interrupt

    // Construct and print register value
    ControlRegister *p;
    p->bits.enable = e;
    p->bits.mode = m;
    p->bits.interrupt = i;
    p->bits.reserved = 0;
    printf("%d",p->reg);
    return 0;
}

Solving Approach

  • Define a union that overlays:
    • A struct with bitfields: enable, mode, interrupt
    • A raw uint8_t register
  • Read values for enable, mode, interrupt from input
  • Construct the struct, and print the final register as an 8-bit unsigned value

 

 

Upvote
Downvote
Loading...

Input

1 2 1

Expected Output

13