Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int int.operator(int left, int right) &

Tags:

c#

I try to understand this expression:

 static Func<int, bool> isOdd = i => (i & 1) == 1;

But what does this mean?

for example I have i = 3. Then (3 & 1) == 1

or i = 4. Then (4 & 1) == 1

I don't understand this. How can it determine when it is odd or when it is even.

with this method:

public static void Hallo2()
        {
            for (int i = 0; i < 10; i++)
            {
                if (isOdd(i))
                    Console.WriteLine(i + " is odd");
                else
                    Console.WriteLine(i + " is even");
            }

        }

Thank you

like image 370
LikeToDo Avatar asked Dec 24 '22 13:12

LikeToDo


2 Answers

& is bitwise AND operation .net uses 32 bit integers but for this example I will use 4 bits, with the left bit being the least significant bit.

The operation 3 & 1. Looks at the numbers in binary so 1100 and 1000 and will output the number where both values are . 1000 = 1.

4 & 1 is 0010 and 1000 so 0000 = 0

It's basically checking if the first (or least significant bit) is 1, if it is we know the number is odd.

like image 199
Dale Avatar answered Dec 26 '22 03:12

Dale


Try to convert it to bits so you can visualize it:

3 = 0011, while 1 = 0001. So 0011 & 0001 will result with 0001.
If you did 3 & 2 == 2 you would also get true since 0011 & 0010 will result with 0010.
Similarly, 8 & 2 == 2 will result with false, since 8 is 0100 and 2 is 0010, so the result of a bitwise and will be 0000.

like image 35
Zohar Peled Avatar answered Dec 26 '22 01:12

Zohar Peled