1

sorry this is probably 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?

1
  • The better test is to find out what 2 & 3 returns. Commented Oct 25, 2010 at 19:40

3 Answers 3

9

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).
Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

3

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.