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);
}
n
to get the unsigned long int
value.lu
prefix to the literal 1
to use unsigned long
instead of int
to prevent overflow in the shift operation.set_bit
is not used and no return
statement is used, so the return type should be void
.stdio.h
should be included to use printf()
.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);
}