Monday, May 24, 2010

Accessing bits in C?

Say I have a bitfield like this:





typedef struct


{


unsigned char bit0:1;


unsigned char bit1:1;


unsigned char bit2:1;


unsigned char bit3:1;


unsigned char bit4:1;


unsigned char bit5:1;


unsigned char bit6:1;


unsigned char bit7:1;


}io_reg;





now I want to assign a unsigned char value to a io_reg type data so that I can access the bits of it. How can I do that? Please help me.

Accessing bits in C?
You can always create a union:





union {


unsigned char val;


typedef struct {


unsigned char bit0:1;


unsigned char bit1:1;


unsigned char bit2:1;


unsigned char bit3:1;


unsigned char bit4:1;


unsigned char bit5:1;


unsigned char bit6:1;


unsigned char bit7:1;


} bits;


} io_reg;





In this way, if you want to assign the entire unsigned char value, you can just use:





io_reg regUnion;


regUnion.val = value;





If you want to access the bits just do this:





regUnion.bits.bit0





etc.

survey for cash

No comments:

Post a Comment