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
&
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With