It's been a while since I've programmed in C and done any bit masking.
My problem is that throughout my device startup, my device driver is initializing bits in registers but only some of them are suppose to be mutable. I know which bits are mutable, and I know what they're suppose to be depending on the memory location.
For example: $0x00AA should always have the format 0b101XXX01 where the X's are mutable and everything else should stay constant. The function currently takes in an address, and a value and simply sets that value to that address. I need to modify it, so that even if the function is passed in 0b11111111 for register $0x00AA it should be set to 0b10111101. Likewise, for 0b00000000 to 0b10100001.
You can first mask out anything except the mutable bits with bitwise AND, then add in the constant bits with bitwise OR.
void set_register(uint8_t value) {
const uint8_t MUTABLE_BITS = 0x1C; // 0b00011100 <- only mutable bits
const uint8_t CONSTANT_BITS = 0xA1; // 0b10100001 <- constant 1-bits
value &= MUTABLE_BITS; // remove any non-mutable bits
value |= CONSTANT_BITS; // add the constant bits
my_register = value;
}
This approach has the questionable feature of hard-coding the value of the constant bits (as per the name “constant”). Another approach would be to set only the mutable bits and take the values for the rest from the register itself (bitwise AND with the complement of the mutable bits mask), e.g.:
void set_register(uint8_t value) {
const uint8_t MUTABLE_BITS = 0x1C; // 0b00011100 <- only mutable bits
value &= MUTABLE_BITS; // remove any non-mutable bits
value |= my_register & ~MUTABLE_BITS; // take other bits from register
my_register = value;
}
(As for the requirement to do this for multiple registers with different masks, I would expect that they be sufficiently limited in number that you can just set them one by one. If you really need a function that takes in a pointer and a value, you must then check that pointer against the known guarded addresses and obtain the appropriate mask somehow. Choices for that range from if
/else
to switch
to binary search to some kind of hash map.)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments