简体   繁体   中英

C: Ampersand in front of a number

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.

x = n & 5;

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:

n           &    5     = x
1 (0b0001)  &  0b0101  = 1  (0b0001)
2 (0b0010)  &  0b0101  = 0  (0b0000)
3 (0b0011)  &  0b0101  = 1  (0b0001)
4 (0b0100)  &  0b0101  = 4  (0b0100)
5 (0b0101)  &  0b0101  = 5  (0b0101)
6 (0b0110)  &  0b0101  = 4  (0b0100)
7 (0b0111)  &  0b0101  = 4  (0b0100)
8 (0b1000)  &  0b0101  = 0  (0b0000)
9 (0b1001)  &  0b0101  = 1  (0b0001)

That's the "bitwise and" operator. Normally, it takes two integers, and returns an integer that has only the bits set that are in both of it's parameters.

base10 base2
6       0110
3       0011
6&3     0010   (=2)

There's also "bitwise or" | which sets bits that either one has set.

base10 base2
6       0110
3       0011
6|3     0111   (=7)

and there's "bitwise xor" ^ which sets bits that are different.

base10 base2
6       0110
3       0011
6^3     0101   (=5)

It's a bitwise AND operator. The value of n is being ANDed with 5.

You were already told that in this case it's a binary and. But this requires a bit more explanation. In C and other C-like languages there are two & operators. One is unary the other binary .

A unary operator acts on a single value alone, while a binary operator takes in two values. In C binary operators take precedence over unary ones. If you write

int b;
int *a = &b;

Then b is the only value the operator can work on. If you write however

int c, d;
int d = c & d;

then the operator has two values to work with and the binary interpretation takes precedence over the unary interpretation. Note that this does not only apply to the & operator, but also its counterpart *

int *f;
int h = *f;

But also

int i,j;
int k = i * j;

Like with all operators, precedence can be overridden with parentheses:

int l, *m;
int n = l * (*m);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM