3

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

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jamil
  • 45
  • 4

2 Answers2

8

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)

Roman Hocke
  • 4,137
  • 1
  • 20
  • 34
4

In general x = (x & ~mask) | (y & mask) copies the bits in mask position from y to x.

In OP's case mask = 0xF000 and y = 0x2000.

dxiv
  • 16,984
  • 2
  • 27
  • 49