Home > Net >  Invalid operands to binary errors (have 'long unsigned int *' and 'int')
Invalid operands to binary errors (have 'long unsigned int *' and 'int')

Time:07-22

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 n to get the unsigned long int value.
  • You should use lu prefix to the literal 1 to use unsigned long instead of int to prevent overflow in the shift operation.
  • The return value of 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);
}

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)

  • Related