64. Decode ADC Result Using Union Bitfields

#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); // Read hexadecimal input

    ADC_Result result;
    result.adc_reg = reg;

    printf("Channel: %u\n", result.channel);
    printf("ADC Value: %u", result.adc_value);
    return 0;
}

What is this about?

This mimics a real ADC result register layout where raw analog values and their source channel are packed into one word. 

Why it’s important in firmware?

  • Real hardware often overlays multiple fields into one register
  • Efficient parsing without using bit masking everywhere
  • Cleaner access via result.channel and result.adc_value
     

Solution Logic

  • Bitfield order matches hardware layout
  • 12 LSBs used for ADC result
  • Top 4 bits for channel
  • Union lets us access both the full value and individual fields

     
Loading...

Input

0xC3F5

Expected Output

Channel: 12 ADC Value: 1013