I created a MACRO to see if a bit is set or not. Code is printing 0 instead of 1.
#define IS_BIT_SET(n,x) ((n&(1<<x)!=0)?1:0)
int main(){
printf("%d \n",IS_BIT_SET(8,3));
}
I created a MACRO to see if a bit is set or not. Code is printing 0 instead of 1.
#define IS_BIT_SET(n,x) ((n&(1<<x)!=0)?1:0)
int main(){
printf("%d \n",IS_BIT_SET(8,3));
}
The != operator has a higher precedence than &.
So your:
n & (1 << x) != 0
is equivalent to:
n & ((1 << x) != 0)
Which, for any value of x that gives a well-defined result, is equivalent to:
n & 1
Which isn't what you want.
To fix this. replace your define with:
(((n & (1 << x)) != 0) ? 1 : 0)
Also, your arguments should probably be wrapped in parentheses if you plan on using this in a more complex situation:
((((n) & (1 << (x))) != 0) ? 1 : 0)
Instead of using a ternary, you can use the fact that the != yields an int of value 0 or 1:
(((n) & (1 << (x))) != 0)
Alternatively, you can skip the comparison to 0, and cast to bool and back to int:
((int) (bool) ((n) & (1 << (x))))
Or stick with the ternary, dropping the comparison to 0:
(((n) & (1 << (x))) ? 1 : 0)
Which one you choose of these last three is a matter of opinion and preference.
The comparison != has higher precedence than & so it's done first. Your code therefore is doing 8 & ((1 << 3) != 0) which is 8 & 1. You need to add parentheses:
#define IS_BIT_SET(n,x) (((n & (1 << x)) != 0) ? 1 : 0)
int main(){
printf("%d \n",IS_BIT_SET(8,3));
}
Now it will be understood as (8 & (1 << 3)) != 0 as you want it to be.