开发者

c# syntax & symbol

sorry this is pro开发者_运维问答bably an embarassing noob question for c#, but I came across the following syntax and wasn't exactly sure what it was doing...

what does the & symbol do in a c# expression with numbers?

for instance, 1 & 1 returns 1?


In the case you mention, it's the bitwise AND operator - it performs the AND operation on each pair of corresponding bits for the 2 integers and returns the result, also as an integer. 1 & 1 == 1 because ANDing a binary number with itself produces the same number - all the zero bits will be projected to zero (false and false is false), while all the one bits will be projected to one (true and true is true).

In C#, &can also serve as:

  1. the non short-circuiting logical AND operator: returns true if both its boolean operands are true. Unlike &&, it will evaluate the value of its second operand even if the first operand has evaluated to be false. It's use is not recommended.
  2. the unary address operator (requires unsafe context).


Bitwise AND operator &

The & (bitwise AND) operator compares each bit of its first operand to the corresponding bit of the second operand. If both bits are 1's, the corresponding bit of the result is set to 1. Otherwise, it sets the corresponding result bit to 0.

Both operands must have an integral or enumeration type. The usual arithmetic conversions on each operand are performed. The result has the same type as the converted operands.

bit pattern of a           0000000001011100
bit pattern of b           0000000000101110
bit pattern of a & b       0000000000001100

Note: The bitwise AND (&) should not be confused with the logical AND. (&&) operator. For example,

1 & 4 evaluates to 0

while

(1 != 0) && (4 != 0) evaluates to true

C++ source, I adapted it a bit

Some articles:

C# And Bitwise Operator

Bitwise operators in c# OR(|), XOR(^), AND(&), NOT(~)

C# Logical Bitwise Operators


As pointed out it's the bitwise AND operator. Usually you use it to compare if certain bits are set in a number, i.e. if you want to check if the 3rd bit is set you could test this by doing.

bool isBitSet = (myNumber & 4) > 0;

You can also cancel out bits of a number by "AND"ing it with a bit mask, i.e. if you want to only look at the two least significant bits of a number:

int lowBits = myNumber & 3;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜