views:

243

answers:

4

In this code:

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

what is the meaning of (i & 1) == 1?

+2  A: 

That is checking if the last bit is on (which makes it odd). Note that isn't specifically to linq, you can do it on sql or c# code.

eglasius
+4  A: 

'&' is the bitwise and operator. &'ing with 1 eliminates all other binary digits, leaving 0 if the number is even, 1 if it is odd.

That is a hacker's way of doing it. A mathematician would of course write ((i % 2) == 1) instead, using modulo 2 arithmetic! Whereas a software engineer would write !IsEven(i), reusing a library function and earning reuse brownie points... :-)

Now, whether any of these are more efficient depends on the compiler and CLR -- and in this case, also on who gets to handle the LINQ expression tree, and what that recipient is prepared to deal with.

Pontus Gagge
Ed Swangren
Don't be too sure. The compiler and IL JIT executor has greater degrees of freedom than you'd imagine...
Pontus Gagge
A software engineer who happens to like to use extension methods for clear and terse C# might write i.IsNotEven().
Martin R-L
+10  A: 

Bitwise AND. In this case, checking whether the last bit in i is set. If it is, it must be an odd number since the last bit represents 1 and all other bits represent even numbers.

HTH, Kent

Kent Boogaart
+4  A: 

& is a bitwise AND operator, AND being one of the fundamental operations in a binary system.

AND means 'if both A and B is on'. The real world example is two switches in series. Current will only pass through if both are allowing current through.

In a computer, these aren't physical switches but semiconductors, and their functionality are called logic gates. They do the same sorts of things as the switches - react to current or no current.

When applied to integers, every bit in one number is combined with every bit in the other number. So to understand the bitwise operator AND, you need to convert the numbers to binary, then do the AND operation on every pair of matching bits.

That is why:

00011011 (odd number)
AND
00000001 (& 1)
== 
00000001 (results in 1)

Whereas

00011010 (even number)
AND
00000001 (& 1)
==
00000000 (results in 0)

The (& 1) operation therefore compares the right-most bit to 1 using AND logic. All the other bits are effectively ignored because anything AND nothing is nothing.

This is equivalent to checking if the number is an odd number (all odd numbers have a right-most bit equal to 1).

The above is adapted from a similar answer I wrote to this question.

thomasrutter