What does this line (x = n & 5;) mean in the code below? As far as I know ampersand is used for pointers. I was not expecting this code to compiled, but it compiled and ran fine. The results I got is
0,1,0,1,4,5,4,5,0,1,
#include <stdio.h>
int main(void){
int x, n;
for (n = 0; n < 10; n++){
x = n & 5;
printf("%d,", x);
}
printf("\n");
return 0;
}
In this case it’s bitwise AND.
will AND 5 (which is 0b101) with whatever is in
n.AND works on the bits that represent the values. The result will have a 1 if both values have a 1 in that position, 0 otherwise.
Since we’re ANDing with 5, and there are only 4 values you can make with the two bits in 0b101, the only possible values for x are 1, 4, 5 and 0. Here’s an illustration: