bitmask - C Bit masking registers -


it's been while since i've programmed in c , done bit masking.

my problem throughout device startup, device driver initializing bits in registers of them suppose mutable. know bits mutable, , know they're suppose depending on memory location.

for example: $0x00aa should have format 0b101xxx01 x's mutable , else should stay constant. function takes in address, , value , sets value address. need modify it, if function passed in 0b11111111 register $0x00aa should set 0b10111101. likewise, 0b00000000 0b10100001.

you can first mask out except mutable bits bitwise and, add in constant bits bitwise or.

void set_register(uint8_t value) {     const uint8_t mutable_bits = 0x1c;  // 0b00011100 <- mutable bits     const uint8_t constant_bits = 0xa1; // 0b10100001 <- constant 1-bits      value &= mutable_bits; // remove non-mutable bits     value |= constant_bits; // add constant bits     my_register = value; } 

this approach has questionable feature of hard-coding value of constant bits (as per name “constant”). approach set mutable bits , take values rest register (bitwise , complement of mutable bits mask), e.g.:

void set_register(uint8_t value) {     const uint8_t mutable_bits = 0x1c;  // 0b00011100 <- mutable bits      value &= mutable_bits; // remove non-mutable bits     value |= my_register & ~mutable_bits; // take other bits register     my_register = value; } 

(as requirement multiple registers different masks, expect sufficiently limited in number can set them 1 one. if need function takes in pointer , value, must check pointer against known guarded addresses , obtain appropriate mask somehow. choices range if/else switch binary search kind of hash map.)


Comments