What is the meaning of the & operator?

c# .net linq operators

420 просмотра

4 ответа

In the following code:

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

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

Автор: kpax Источник Размещён: 13.11.2019 11:29

Ответы (4)

12 плюса


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.

Автор: Kent Boogaart Размещён: 15.03.2009 09:14

4 плюса

'&' 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 Размещён: 15.03.2009 09:13

4 плюса

& 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)
00000001 (& 1)
00000001 (results in 1)


00011010 (even number)
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 Размещён: 15.03.2009 12:25

2 плюса

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 Размещён: 15.03.2009 09:13