views:

676

answers:

7

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,
    Put = 1 << 2,
    Delete = 1 << 3,
    Head = 1 << 4
}

and I'm just curious as to what "<<" does.

+30  A: 

That's the left bitshift operator. It shifts the bit pattern of the left operand to the left by the number of binary digits specified in the right operand.

Get = 1 << 0, // 1
Post = 1 << 1, // 2
Put = 1 << 2,  // 4
Delete = 1 << 3, // 8
Head = 1 << 4  // 16

This is semantically equivalent to lOperand * Math.Pow(2, rOperand)

Adam Robinson
+1 for actually showing what the left bitshift is doing in this case.
auujay
Or More Specifically: 00001, 00010, 00100, 01000, 10000
zipcodeman
"by the number of binary digits specified in the right operand" - actually, that isn't *quite* right; for 32-bit, for example, it only considers the first 5 bits, so `<< 33` is **identical** to `<< 1`. Likewise in 64-bit math, `<< 65` is **identical** to `<< 1`. And right-shift is more complex again, as you need to consider the sign to know what to backfill with.
Marc Gravell
+41  A: 

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.

Aaronaught
Thanks for the answer - makes sense now!
Simon G
+9  A: 

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 = 1
    Post = 1 << 1, // 00000001 -> 00000010 = 2
    Put = 1 << 2,  // 00000001 -> 00000100 = 4
    Delete = 1 << 3, // 00000001 -> 00001000 = 8
    Head = 1 << 4 // 00000000 -> 00010000 = 16
}

More info at http://www.blackwasp.co.uk/CSharpShiftOperators.aspx

Fabian
+7  A: 

"Bit shift left." 1 << 0 means "take the integer value 1 and shift its bits left by zero bits." I.e., 00000001 stays unchanged. 1 << 1 means "take the integer value 1 and shift its bits left one place." 00000001 becomes 00000010.

Dathan
For your first example, I think you meant "by zero bits", but the rest is correct.
Adam Robinson
@Adam Thanks, you're absolutely right. I've updated the post.
Dathan
+1  A: 

Some info on the bitwise operators - > Most common C# bitwise operations

Morten Anderson
+2  A: 

I know this answer is pretty much solved, but I thought the visualization might help someone.

[Fact] public void Bit_shift_left()
{
    Assert.Equal(Convert.ToInt32("0001", 2), 1 << 0); // 1
    Assert.Equal(Convert.ToInt32("0010", 2), 1 << 1); // 2
    Assert.Equal(Convert.ToInt32("0100", 2), 1 << 2); // 4
    Assert.Equal(Convert.ToInt32("1000", 2), 1 << 3); // 8
}
Mark