71. Decode ADC Result Using Union Bitfields

Back To All Submissions
Previous Submission
Next Submission

Code

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

typedef union {
    struct {
        uint16_t adc_value : 12;
        uint16_t channel   : 4;
    };
    uint16_t adc_reg;
} ADC_Result;

int main() {
    uint16_t reg;
    scanf("%hx", &reg);

    // Fill union and print channel and adc_value
    ADC_Result result;

    //1. Assign the input register to the adc_reg member
    result.adc_reg = reg;

    //2. Assing the channel and adc values to the struct members from the uniorns
    uint16_t channel = result.channel;
    uint16_t value = result.adc_value;

    printf("Channel: %u\n", channel);
    printf("ADC Value: %u\n", value);

    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote