简体   繁体   中英

How does this C# code snippet work?

Can someone explain the following piece of code

int x = 45; 
int y = x &= 34;

It assigns 32 to y

It's performing a bitwise "and" as a compound assignment operator. It's equivalent to:

int x = 45;
x = x & 34;
int y = x;

Now 45 = 32 + 8 + 4 + 1, and 34 = 32 + 2, so the result of a bitwise "and" is 32.

Personally I think that using a compound assignment operator in a variable declaration is pretty unreadable - but presumably this wasn't "real" code to start with...

int x = 45; 
int y = x &= 34;
Gives: y = 32

int x = 45;  // 45 = 101101
             // 34 = 100010
x = x & 34;  // 101101
             // 100010 &
             // --------
             // 100000  ( = 32 )

int y = x;    //  y = 32

It's a bitwise operation, more information can be found here:

http://msdn.microsoft.com/en-us/library/sbf85k1c%28VS.80%29.aspx

It is equivalent to:

int x = 45;
x = x & 34;
int y = x;

The & operator for integral types computes the logical bitwise AND of its operands.

看起来像一个按位AND,它由&=快捷方式表示法分配给x,并且也分配给y

45 = 101101(binary)
34 = 100010(binary)

45 & 34 = 100000(binary) = 32

Here x &= 34 is used both as an assignment and an expression. It calculates the value of x & 34 , assigns it to x , and the value of the expression is what's assigned.

The result of the bitwise and operation 45 & 34 is 32 , which is assigned to x, and then also to y.

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