Вопрос:

What is the meaning of the & operator?

c# .net linq operators

420 просмотра

4 ответа

149 Репутация автора

In the following code:

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

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

Автор: kpax Источник Размещён: 15.03.2009 09:10

Ответы (4)


2 плюса

33656 Репутация автора

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

4 плюса

16019 Репутация автора

'&' 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

12 плюса

149728 Репутация автора

Решение

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 плюса

94553 Репутация автора

& 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 Размещён: 15.03.2009 12:25
32x32