Basically the questions in the title. I\'m looking at the MVC 2 source code:
[Flags]
public enum HttpVerbs {
Get = 1 << 0,
Post = 1 << 1,
The expression (1 << N)
uses a Bit Shift in c#.
In this case it's being used to perform a fast integer evalution of 2^N, where n is 0 to 30.
A good tool for young whippersnappers developers that don't understand how bit shifts work is Windows Calc in programmer mode, which visualises the effect of shifts on signed numbers of various sizes.
The Lsh
and Rsh
functions equate to <<
and >>
respectively.
Evaluating using Math.Pow inside the loop condition is (on my system) about 7 times slower than the question code for N = 10, whether this matters depends on the context.
Caching the "loop count" in a separate variable would speed it up slightly as the expression involving the list length would not need to be re-evaluated on every iteration.
Thats bit shifting. Its basically just moving the bits to the left by adding 0's to the right side.
public enum HttpVerbs {
Get = 1 << 0, // 00000001 -> 00000001 = 1
Post = 1 << 1, // 00000001 -> 00000010 = 2
Put = 1 << 2, // 00000001 -> 00000100 = 4
Delete = 1 << 3, // 00000001 -> 00001000 = 8
Head = 1 << 4 // 00000001 -> 00010000 = 16
}
More info at http://www.blackwasp.co.uk/CSharpShiftOperators.aspx
It is implied in a number of answers but never stated directly...
For every position that you shift a binary number left, you double the original value of the number.
For example,
Decimal 5 binary shifted left by one is decimal 10, or decimal 5 doubled.
Decimal 5 binary shifted left by 3 is decimal 40, or decimal 5 doubled 3 times.
It is Bitwise shift left it works by shifting digits of binary equivalent of number by the given (right hand side) numbers.
so:
temp = 14 << 2
binary equivalent of 14 is 00001110
shifting it 2 times means pushing zero from right hand side and shifting each digit to left side which make it 00111000
equals to 56.
In your example:
i < (1 << list.Count)
and so on. In general it is equal 2 ^ list.Count
(2 raised to the power of list.Count)
In addition to Selman22's answer, some examples:
I'll list some values for list.Count
and what the loop would be:
list.Count == 0: for (int i = 0; i < 1; i++)
list.Count == 1: for (int i = 0; i < 2; i++)
list.Count == 2: for (int i = 0; i < 4; i++)
list.Count == 3: for (int i = 0; i < 8; i++)
And so forth.
That would be the bitwise left shift operator.
For each shift left, the value is effectively multiplied by 2. So, for example, writing value << 3
will multiply the value by 8.
What it really does internally is move all of the actual bits of the value left one place. So if you have the value 12 (decimal), in binary that is 00001100
; shifting it left one place will turn that into 00011000
, or 24.