All submissions

Register Bitfields Using Struct Overlay

 

#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);

    // Construct and print register value
    // Declare the union variable
    ControlRegister ctrl;

    // Initialize the entire 8-bit register to zero.
    // This is important to ensure the 'reserved' bits are 0.
    ctrl.reg = 0;

    // Assign the input values directly to the bitfields
    ctrl.bits.enable = e;
    ctrl.bits.mode = m;
    ctrl.bits.interrupt = i;

    // Print the final combined value from the raw register view
    printf("%u\n", ctrl.reg);
   
}

 

 

 

Loading...

Input

1 2 1

Expected Output

13