What do two left-angle brackets “<<” mean in C#?

前端 未结 15 1938
长情又很酷
长情又很酷 2020-12-12 13:55

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,         


        
相关标签:
15条回答
  • 2020-12-12 14:11

    Previous answers have explained what it does, but nobody seems to have taken a guess as to why. It seems quite likely to me that the reason for this code is that the loop is iterating over each possible combination of members of a list -- this is the only reason I can see why you would want to iterate up to 2^{list.Count}. The variable i would therefore be badly named: instead of an index (which is what I usually interpret 'i' as meaning), its bits represent a combination of items from the list, so (for example) the first item may be selected if bit zero of i is set ((i & (1 << 0)) != 0), the second item if bit one is set ((i & (1 << 1)) != 0) and so on. 1 << list.Count is therefore the first integer that does not correspond to a valid combination of items from the list, as it would indicate selection of the non-existant list[list.Count].

    0 讨论(0)
  • 2020-12-12 14:13

    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)

    0 讨论(0)
  • 2020-12-12 14:20

    The purpose of the loop is most likely to generate or operate on all subsets of the set of items in the list. And the loop body most likely also has a good bit (har har) of bitwise operations, namely both another left-shift and bitwise-and. (So rewriting it to use Pow would be mighty stupid, I can hardly believe there were so many people that actually suggested that.)

    0 讨论(0)
提交回复
热议问题