Kernighan and Ritchie confusion

Hi,

I am working my way through the Kernighan and Ritchie book alongside my university course. I have been comfortable with all exercises so far until this one. The K&R wiki has the code available but I cannot understand it.

If anyone has a minute to break down this code for me it would be much appreciated :)

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:

`SetBits(unsigned int x, int p, int n, unsigned int y)`

{

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

}

The example I am working with

Before I prompt the user to input their own values of x, p, n and y I am sending set values I know the desired output for.

Code:

`#include <stdio.h>`

unsigned int SetBits(unsigned int x, int p, int n, unsigned int y);

void DisplayBits(unsigned value);

int main()

{

unsigned int k;

k = SetBits(170, 5, 3, 167);

DisplayBits(k);

printf("%d\n", k);

return 0;

}

unsigned int SetBits(unsigned int x, int p, int n, unsigned int y)

{

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

}