Question : What's the best way to modify bitfields

If I have to modify some individual bits in a hardware register, I can do this
1:
2:
3:
4:
5:
6:
7:
8:
9:
struct Bitwise
{
	char PM:3;
	char DR:2;
	char XEN:1;
	char YEN:1;
	char ZEN:1;
}foo;

Thanks to phoffric (Expert's Exchange guru), I have realised that it is not an efficient solution for portability. It I want to modify 'DR' (bits 3,2) and if Iam writing binary 11 then it is easy.
1:
2:
3:
4:
5:
6:
7:
8:
9:
char reg1 = 0x34; //some value
char DR = (0x3 << 2);
UpdateReg(DR);

UpdateReg(char val)
{
  reg1 |= DR; 
}

The OR operator works if the value is binary 11.
 If I want to change a bit from 1 to 0, it can be done if I know the bit position.
for ex: reg1 &= ~(1 << 3)

But in the below code
1:
2:
3:
DR = (0x01 << 3)
UpdateReg(DR)

My intention is just to change bits 3,4. But I lost that information is lost in the function UpdateReg.
In the UpdateReg function it will look like binary 00001000. Now I cannot apply the above way of converting a 1 to 0. I must also send the bit numbers that are to be modified.

Is there a simpler way of doing this?

Thanks

Answer : What's the best way to modify bitfields

>>What's the best way to modify bitfields used for hardware register
is to not use bitfields.

>> I want to modify 'DR' (bits 3,2)
I don't see how that matches your bitfields DR
==============

See if this is what you are driving for:

In any case, it seems that you want your UpdateReg() function to be general enough to handle any scenario.

UpdateReg( char mask, char newPattern );
         where mask is a set of arbitrarily placed bits that will clear
I'm assuming that you can read the register in a temp variable, and then manipulate it, and finally write it back to the HW register. (This isn't always true, since sometimes reading the HW register changes the value.)

So the mask is adapted to first clear the corresponding bits in the temp variable (after you read the HW register). Then, using the mask again with the newPattern, I now have the valid set of bits (or 0's) to or into the temp register. Then write the temp back to the HW.
Random Solutions  
 
programming4us programming4us