Hi All, I have a struct:
union U { unsigned char c; struct { unsigned char bit0 : 1; unsigned char bit1 : 1; unsigned char bit2 : 1; . . . }S; }; }
hi, first of all, do never rely on that bits will be placed into union as you wish. For example, try this simple code:
union { unsigned char my_chars[2]; struct { unsigned char bit0 : 1; unsigned char bits1 : 6; unsigned char bits2 : 7; unsigned char bit1 : 1; unsigned char bit2 : 1; } my_bits; } my_union; void main(void) { unsigned char x; x = sizeof(my_union); }
unsigned char bdata my_bits; sbit my_bit0 = my_bits^0; sbit my_bit1 = my_bits^1; sbit my_bit2 = my_bits^2; void main(void) { my_bits = 0x00; my_bit1 = 1; while(1) { if (my_bits & 0x06) // check either bit 1 or 2 set my_bits &= ~0x06; // reset both else my_bits++; } }
Thanks Oleg for your example and explanation. It does work if it is bit addressable. My question is more of a C language that works for standard data type where byte is the smallest addressing. Any other ideas? Thanks, Anh
hi, My question is more of a C language that works for standard data type where byte is the smallest addressing My suggestion is still the same: do not use union. It may be done with next way:
unsigned char my_bits; #define BIT0_MASK (1) #define BIT1_MASK (1<<1) #define BIT2_MASK (1<<2) void main(void) { my_bits = 0x00; // clear variable my_bits |= BIT1_MASK; // set bit 1 while(1) { if (my_bits & (BIT1_MASK|BIT2_MASK)) // check either bit 1 or 2 set my_bits &= ~(BIT1_MASK|BIT2_MASK); // reset both else my_bits++; } }