Taking 2-6 as an example, I used the values 17, 4, 3, 15.
So:
x = 17 or 10001
p = 4
n = 3
y = 15 or 01111
Using my example numbers what we need to do here is take the three ls bits from y (111) and insert them into x starting at position 4. This will give us 11111 or 31. We need to clear the 3 bits in x starting at position four, clear all of the bits in y except for the rightmost 3 bits, move them to position four and OR the two values together.
1st: Shift all ones to the left n positions ~0 << n = 1111111111111000
2nd: Place all ones at the rightmost n positions ~(~0 << n) = 0000000000000111
3rd: Shift these n 1 bits to position p and set n bits to zeros starting at position p.
~(~(~0 << n) << (p-n)) = 1111111111110001
4th: And this mask with x to clear the n bits of x at position p = 10001
(I am sure that everyone realizes that all we did is get right back to our starting number,
but we have to do this in order to tell the program what position we want to start at, and
how many bits we would like to work with. What if p is 6 and n is four?)
Next clear all bits in y except for the rightmost n bits:
1st: ~(~0 << n) places all ones in the rightmost n positions. 0000000000000111
2nd: y & ~(~0 << n) Select the rightmost n bits of y 0000000000000111
3rd: (y & ~(~0 << n)) << (p-n) Place n bits of y at position p 0000000000001110
Finally OR the two outcomes together
0000000000010001 = 17
0000000000001110 = 7 OR=
0000000000011111 = 31
The result becomes:
return x & ~(~(~0 << n) << (p-n)) | (y & ~(~0 << n)) << (p-n);
I am sorry if this is at all hard to read. I was somewhat limited in my formatting ability. (I am sure this is my fault) I hope that this helps, I have been stuck on this particular exercise for quite a while, and finally came up with this solution today, after looking at this very thread, so I figured that I would post the right answer, as well as, an explanation as to why it is the right answer, which is something that I have found lacking in many answers that I have seen.