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)
{
unsigned int tmpmask;
tmpmask = ~(~0U << xfrnum)
origvar &= tmpmask;
tmpmask = ~(tmpmask << xfradr);
destvar &= tmpmask;
origvar <<= xfradr;
destvar ^= origvar;
return destvar;
}
int main(void)
{
unsigned int origvar, destvar, spchldr;
int xfrnum, xfradr;
for(origvar = 0; origvar <= 250; origvar += 49)
for(destvar = 0; destvar <= 250; destvar += 49)
for(xfrnum = 0; xfrnum <= 8; xfrnum++)
for(xfradr = 0; xfradr <= 8; xfradr++){
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.