#include <stdio.h>
#include <stdint.h>
#define ADC_VALUE(reg) (reg & 0x0FFF)
#define CHANNEL_VALUE(reg) ((reg & 0xF000) >> 12U)
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", ®);
// Fill union and print channel and adc_value
uint16_t adc_val = ADC_VALUE(reg);
uint8_t channel = CHANNEL_VALUE(reg);
printf("Channel: %d\n", channel);
printf("ADC Value: %d\n", adc_val);
return 0;
}
Bitfields
Input: 0x10FF
Output:
Channel: 1
ADC Value: 255
0x10FF -> 0b 0001 0000 1111 1111
for channel the mask -> 0xF000
shift to the right by 12 to get the channel
for adc-val the mask -> 0x0FFF
Plan:
- create a local object from the union
- create a mask for the adc value
- create a mask for the channel value
- print the channel and the adc value
Input
0xC3F5
Expected Output
Channel: 12 ADC Value: 1013