开发者

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.


Looks like a bitwise AND, which is assigned to x by the &= shortcut notation, and is also assigned to y.


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.


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

45 & 34 = 100000(binary) = 32
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜