Hi, I've been reading The C Programming Language book and one of the excersises is to write a setbits(x, p, n, y) function that returns x with the n bits that begin at position p set to the rightmost n bits of y and am really stuck on how to do it.

Here's my code so far, all i need is to finish the result variable:

could anyone guide me through it with examples or anything.Code:/* setbits.c * program to return x with the n bits at position p to the rightmost n bits of y */ #include <string.h> #include <stdio.h> #include <stdlib.h> #include <math.h> unsigned setbits(unsigned *x, int *p, int *n, unsigned *y); void binary_out(unsigned *num); int main(int argc, char **argv) { if (argc < 5) { fprintf(stderr, "Usage: %s <num1> <num2> <num3> <num4>\n", argv[0]); return -1; } unsigned a = atoi(argv[1]); int b = atoi(argv[2]); int c = atoi(argv[3]); unsigned d = atoi(argv[4]); setbits(&a, &b, &c, &d); return 0; } void binary_out(unsigned *num) { int i; for (i = 256; i > 0; i>>=1) { if ((*num & i) == i) printf("%d", 1); else printf("%d", 0); } printf("\n"); } // return x with the n bits at position p to the rightmost n bits of y unsigned setbits(unsigned *x, int *p, int *n, unsigned *y) { printf("x is: "); binary_out(x); printf("y is: "); binary_out(y); unsigned result = ((*x printf("and the result is: "); binary_out(&result); }

Thanks.