Decode ADC Result Using Union Bitfields

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);
    
    ADC_Result r;
    r.adc_reg = reg;
    // Fill union and print channel and adc_value
    printf("Channel: %u\n", r.channel);
    printf("ADC Value: %u\n", r.adc_value);
    return 0;
}

Solving Approach

  1. Union overlays memory → lets us see the same 16-bit value in two ways.
  2. Bitfields split the 16-bit value:
    • 12 bits → ADC result
    • 4 bits → channel
  3. Read 16-bit hex input using %hx.
  4. Store into union → automatically breaks into channel + adc_value
  5. Print fields.

 

 

Upvote
Downvote
Loading...

Input

0xC3F5

Expected Output

Channel: 12 ADC Value: 1013