Thread: help with setbits function

1. help with setbits function

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:
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);
}```
could anyone guide me through it with examples or anything.
Thanks.

2. The line below is missing part of the code; it will not compile as written.
Edit: And, since your comment is not enough for me to guess what it should do; I can not help you.
I suggest you think on what input should give what output and how you can do that.
Code:
`unsigned result = ((*x`
In spots, looks like poorly written code.
Edit: Poorly written include this function "binary_out"; why does an output only function needed to be passed an pointer.

Other parts look good.

Tim S.

3. yeah, i know the result variable is missing code that's what i need help with.

4. Originally Posted by cprog12
yeah, i know the result variable is missing code that's what i need help with.
And, it does what?
Example input and output?

Since you passed the parameters as pointers; are you planning to change all the input parameters value in the function?

Several year old thread on same topic
Bitwise setbits function (knr 2-6)

5. i need to use bitwise operators to return x with the n bits at position p to the rightmost n bits of y, but i'm stuck on how to write it.

6. Thanks, the thread really helps

Popular pages Recent additions