Search code examples
c++mask

C ++ How to change the value of 4 bits in a 32 bit number


I have a 32-bit register that I need to manipulate. But I only need to change bits 12-15, and leave the rest of the bits unchanged.

Register image

I want to overwrite whatever is in bits 12-15 with 0x2 or 0b0010.

How can I do this in C++?

Here is an example code I have been trying.

#include <iostream>
#include <bitset>

using namespace std;

int main() {
    uint32_t x = 0x4D00D0F0;

    x |= 0x2 << 12; // shifting 0x2 12 bits to the left

    return 0;
}

My solution only seems to shift a 1 to bit 13, why is that?

Can I shift an entire 4-bit hex number?

Bottom line, I want x = 0x4D0020F0


Solution

  • First, mask the original bits out to make sure they are zeroed and won't interfere with the value, you are going to "or" there:

    x & 0xffff0fff

    Then "or" the new bits into place:

    (x & 0xffff0fff) | (0x2 << 12)