How does Unary Operator '&' work

How does the unary operator '&' work ?

In a test project i ran this code:

int num = 50, num2 = 100;

int x = num & num2;

result: x = 32

 int num = 100, num2 = 90;

 int x = num & num2; 

result :x = 64

How is this calculated ?


From MSDN:

Binary & operators are predefined for the integral types and bool. For integral types, & computes the logical bitwise AND of its operands. For bool operands, & computes the logical AND of its operands; that is, the result is true if and only if both its operands are true.

In your case it is integeral type version.

So:

 50 in binary is 00110010     
100 in binary is 01100100     
AND result is    00100000 (32 dec)

Bitwise operator works on bits and perform bit-by-bit operation.

Binary AND Operator copies a bit to the result if it exists in both operands.

(A & B) = 12, i.e., 0000 1100

Binary values

50 (10 ) = 0110010  (2)
100 (10) = 1100100  (2)

And a logical AND is used so only the bits where both values are 1 are now one resulting in:

0100000 (2) = 32 (10)

and

100 (10) = 1100100  (2)
AND
90 (10) =  1011010 (2)
------------------------
64 (10) =  1000000(2)
链接地址: http://www.djcxy.com/p/72662.html

上一篇: 字段打包形成一个字节

下一篇: 一元运营商如何工作?