Saturday, June 6, 2020

Struct with defined number of bits for each member in C

typedef struct _bitfield {
     unsigned one_bit0:1;
     unsigned one_bit1:1;
     unsigned two_bits:2;
     unsigned four_bits:4;
} BITFIELD;


#include
#include

typedef struct _xpto {
int x;
struct {
int p;
unsigned t:1;
}PT;
char o;

} XPTO;

union {
int result;
char byte[2];
struct {
unsigned b0:1;
unsigned b1:1;
unsigned b2:1;
unsigned b3:1;
unsigned b8:28;
} ST;
} adc;

int main(int argc, char *argv[]) {
XPTO myxpto = { .x=10, .PT = { .p=2, .t=1 }, .o='A'};
printf(".x = %d, .PT { .p = %d, .t = %d }, .o = %c\n",myxpto.x,myxpto.PT.p,myxpto.PT.t,myxpto.o);

adc.byte[0] = 1;
adc.byte[1] = 2;
printf("%x\n", adc.result);
adc.ST.b0 = 0;
printf("%x\n", adc.result);
return 0;
}

No comments:

Blog Archive