bits arithmetics

[use case]
some time it is very useful if we can read special bits from a register in c code.
Things like the bits from position 4 to position 8 in a 32bits register.

In other case it could be more useful to rewrite the bits in a register, things like the bits from position 4 to postion 8 should habe a new hex value 0xf.

[Solution]

int bits_read(int reg, int pos, int width) { 
  // mask ~(~0 << width) should be like 0...0 1...1 
  return reg >> pos & ~(~0 << width);
}

this function can read the bits from a start position and with a width of the bits you would like to get from the start bit postion.

int bits_write(int reg, int pos, int width, int new_value) {
 // create dynamic mask like 0...0 1...1 0...0
 int mask = (~(~0 << width)) << pos;
 return ( new_value << pos ) & mask | (reg & ~mask);
}

this function allows you to rewrite the bits from the start postion with a certain width of bits with the given new value.

[Reason]

why do we need this kind of function with dynamic masks?

The answer to this question is because the most time we don’t know how long is a register, ist it 8 bits or 32 bits. With these two funktion you can read and rewrite the subbits of a register and it works with register with what ever length.