1. ## Misadventures with bitwise operators

I'm trying to make a program that solves exercise 2-6 in K&R: "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."

While I renamed/reordered the function and variables, so I wouldn't get mixed up, this code should(in theory) do the same thing.

Code:
```#include <stdio.h>

unsigned int xfrbits(unsigned int origvar, unsigned int destvar, int xfrnum, int xfradr)
{
destvar ^= origvar;
return destvar;
}

int main(void)
{
unsigned int origvar, destvar, spchldr;
for(origvar = 0; origvar <= 250; origvar += 49)
for(destvar = 0; destvar <= 250; destvar += 49)
for(xfrnum = 0; xfrnum <= 8; xfrnum++)
spchldr = xfrbits(origvar, destvar, xfrnum, xfradr);
printf("%u, %u, %d, %d : %u\n", origvar, destvar, xfrnum, xfradr, spchldr));
}
return 0;
}```
I understand the principle here(I think), but I want to make sure I'm not getting mixed up.

Here's the logic I used to solve the exercise:

1. Generate bitmask to erase all the bits in origvar not being transfered, apply this mask to origvar.

2. Alter this bitmask to erase the bits to be overwritten by origvar, apply this mask to destvar.

3. Bitshift origvar to place the bits correctly.

4. Apply origvar to destvar to transfer the bits.

Please, be nice if you find problems with this - I mean, tell me exactly what I did wrong, but keep in mind that I had some trouble focusing long enough to write it.

Note: The extra assignment of
Code:
`spchldr = xfrbits(...);`
is just to save screen space for this post; I'd normally call xfrbits inside the printf that follows.

2. Your solution is just a tad overkill. Try to use getbits as your example, and remember that reuse is a good thing. You'll find that the solution really isn't that much longer (and is simpler) than the one for getbits.

>Please, be nice if you find problems with this
Well, it's not correct in that it doesn't do what the exercise asks for. You can test the bit result with something quick and dirty like this:
Code:
```void showbits(unsigned int x)
{
int i;

for (i = 15; i >= 0; i--)
printf("%d", !!(x & (1U << i)));
printf("\n");
}```