1

What does this expression actually mean??

Note - the x and y vars are just sample values.

int x = 3; 
int y = 1; 

if ((x & y) !=0)

I inherited a codebase and am not up to speed on bitwise operators. I have read up, but am still missing something. Help!

3 Answers 3

8

It's comparing the bits in each value. It returns any bits that are set in both numbers.

In your example:

    3:  0011
    1:  0001

3 & 1:  0001
Sign up to request clarification or add additional context in comments.

Comments

2

This checks whether x and y both have at least one common bit set. In the case of your example this would be the true.

Comments

1
if ((x & y) != 0)

This would typically be used to determine whether the value x has a specific bit-flag (y) set. The AND operator returns an integer with only those bits set that are set in both operands.

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.