Search code examples
cbit-manipulationbitwise-operatorsbit

How to bitwise replace a range of bits in one number with the bits of another for incrementing, not affecting lower bits?


I have a 16-bit number, the LSB 4 bits are used as bitfields to check settings, and the MSB 12 bits are used as a number that is incremented. I know that tempNum = (data_bits >> 4) will get me the number out of the larger one. If I want to increment that tempNum by 1 and then put that back into the overall 16-bit number as a replacement without affecting the lower 4 bits, how would I go about doing this? I want to do this using bitwise operations only.


Solution

  • The simplest way to do this would be to increment starting after 4 bits, i.e.:

    data_bits += 1 << 4;
    

    This leaves the lower 4 bits unchanged.