Search code examples
embeddedmicrocontrollerbinary-operators

How to change only part of a register to a number (Examples are doing it wrong?)


I want to write for example the number 32 to the 16-24 bits of a register. This register is 100 bits long and the rest or some of the register contains "reserved bits" that shouldn't be write to (According to the datasheet.) or lets say it contains other values I don't want to change(Previous settings.).

If it was only a few bits I could set each one of them with the R &= ~(1 << x) or R |= 1 << x for each bit. But if it was a number, It'd be a huge pain to turn 32 to binary and do it one by one. I see some of the examples basically do something like R = 0x20 << 16. but I'm confused. wouldn't that ruin every other bit and set the reserved bits to 0 messing with the MCU Operation?


Solution

  • I want to write for example the number 32 to the 16-24 bits of a register. This register is 100 bits long and the rest or some of the register contains "reserved bits" that shouldn't be write to (According to the datasheet.) or lets say it contains other values I don't want to change(Previous settings.).

    You want to perform a Read-Modify-Write. In this case, you are interested in setting bits 16-24 to a specific value. Assuming those values are zero, you can do that like this:

    my_register |= (32 << 16);
    

    This is a Bitwise-OR operation and that is important to note because it keeps whatever the value of the bits were.

    Assuming those values are non-zero, you will want to clear those bits first, then write the new value. You can do that like this:

    my_register &= ~(0xFF << 16); //Clear bits 16-24
    my_register |= (0x20 << 16); //Set bits 16-24 to 32
    

    The above uses Bitwise AND, Bitwise OR, and Bitwise inversion. Again, these operations maintain the values of other bits.

    I see some of the examples basically do something like R = 0x20 << 16. but I'm confused. wouldn't that ruin every other bit and set the reserved bits to 0 messing with the MCU Operation?

    That's not necessarily true. Those bits are likely write protected, or the default value for those bits might be 0 so writing 0 to them has no effect. It just depends on the MCU itself.