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

前端 未结 15 1998
长情又很酷
长情又很酷 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条回答
  •  -上瘾入骨i
    2020-12-12 14:04

    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.

提交回复
热议问题