I'm trying to set a bit at a given position but I keep getting an error can someone help with this?
This is my code:
int set_bit(unsigned long int *n, unsigned int index)
{
long unsigned int value;
value = n | (1 << index);
}
int main(void)
{
int n;
n = 1024;
set_bit(&n, 5);
printf("%lu\n", n);
n = 0;
set_bit(&n, 10);
printf("%lu\n", n);
n = 98;
set_bit(&n, 0);
printf("%lu\n", n);
return (0);
}
CodePudding user response:
- You should dereference the pointer
nto get theunsigned long intvalue. - You should use
luprefix to the literal1to useunsigned longinstead ofintto prevent overflow in the shift operation. - The return value of
set_bitis not used and noreturnstatement is used, so the return type should bevoid. stdio.hshould be included to useprintf().
Try this:
#include <stdio.h>
void set_bit(unsigned long int *n, unsigned int index)
{
*n = *n | (1lu << index);
}
int main(void)
{
int n;
n = 1024;
set_bit(&n, 5);
printf("%lu\n", n);
n = 0;
set_bit(&n, 10);
printf("%lu\n", n);
n = 98;
set_bit(&n, 0);
printf("%lu\n", n);
return (0);
}
CodePudding user response:
your set_bit function is expecting lu pointer (unsigned long int *n) while you are treating it in the function as a lu value (n | (1 << index)).
write it a bit differently - value= *n | (1 << index)
