What is the meaning of the & operator?
420 просмотра
4 ответа
In the following code:
Expression<Func<int, bool>> isOdd = i => (i & 1) == 1;
...what is the meaning of (i & 1) == 1
?
Ответы (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.
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:134 плюса
& 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:252 плюса
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Вопросы из категории :
- c# Преобразовать десятичную в двойную?
- c# Как рассчитать чей-то возраст в C #?
- c# Как вы сортируете словарь по значению?
- c# В чем разница между int и Integer в Java и C #?
- c# Как создать новый экземпляр объекта из Типа
- .net Действительно ли опечатанные классы действительно предлагают преимущества?
- .net Setting Objects to Null/Nothing after use in .NET
- linq LINQ-запрос к DataTable
- linq Условные запросы Linq
- linq Конфликт данных в LINQ
- linq Есть ли способ переопределить пустой конструктор в классе, сгенерированном LINQtoSQL?
- linq Отладка LINQ to SQL SubmitChanges ()
- operators В чем разница между | и || или операторы?
- operators Что делает оператор запятой?
- operators Чем отличаются операторы сравнения PHP (== double equals) и тождества (=== triple equals)?
- operators Как получить десятичное значение при использовании оператора деления в Python?
- operators Что такое операторы побитового сдвига (bit-shift) и как они работают?