1. ## setbits

Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.

Code:
```unsigned setbits(unsigned x, int p, int n, unsigned y)
{
return (x & ((~0 << (p + 1)) | (~(~0 << (p + 1 - n))))) | ((y & ~(~0 << n)) << (p + 1 - n));
}```
Can someone please explain me how does this work:

x & ((~0 <<(p+1))

p = 5;
char x = 0011 0100

0011 0100 &
0011 1111 // this set of bits?
---------------
0011 0100

2. There's a FAQ on bit manipulation that covers each of the operations.

~ is to flip the bits the other way. So ~0 is setting all bits on.
<< shift to the left p+1 times
& what you have shown

What part aren't you understanding? (hint: read the FAQ)

Quzah.

3. edit: its ok, i understand everything now!

4. ## Brackets

Please check the brackets properly, I think you are calculating it wrongly

Code:
`return (x & ((~0 << (p + 1)) | (~(~0 << (p + 1 - n))))) | ((y & ~(~0 << n)) << (p + 1 - n));`

5. and in the first block also,
Code:
`(x & ((~0 << (p + 1)) | (~(~0 << (p + 1 - n)))))`

6. Thx, i got it now .

This is the function i wrote, but what should i do in case x receives a negative value? Should i rather declare setbits as int and then check if x is negative? Seems like the program automaticaly turns it into a positive value if its negative, and thats not good...

Code:
```unsigned setbits(unsigned int x, int p, int n, unsigned int y)
{
if(n < 1 || n>p-1
|| p < 0 || p>sizeof(unsigned)*8)
return 0;

unsigned tmp1 = x&(~((~(~0<<n))<<p+1-n));
unsigned tmp2 = ((y&(~(~0<<n))))<<p+1-n;
return tmp1 | tmp2;
}```

8. x is unsigned, how is it going to be negative?

9. Code:
```int main {

setbits(-250, 5, 3, 15);

return 0;
}```
My compiler actually compiles this, thats why i find it strange.

10. Turn up your compiler warning level then.

Note that the solution you're working on looks a fair bit more complicated than it could be.

11. >Note that the solution you're working on looks a fair bit more complicated than it could be.

It does the job. I couldve written those last 3 lines in 1, but i preffer not to.

12. ## Nice explanation of this on my recent post

Kernighan and Ritchie confusion

I was just doing this exercise and needed it explaining, which someone did very well!